简体   繁体   English

如何在所选选项上设置背景颜色

[英]How to set Background Color on the selected option

I have an international custom dropdown country code selector section in my project and the code is working fine, but the problem I am facing right now is that when a user opens the dropdown list second time, then I am unable to get the first selected option highlighted using css.我的项目中有一个国际自定义下拉国家代码选择器部分,代码工作正常,但我现在面临的问题是,当用户第二次打开下拉列表时,我无法获得第一个选择的选项使用 css 突出显示。

That means, when a user selects an option for the first time on the dropdown, I want that option to be highlighted using the background color property.这意味着,当用户第一次在下拉列表中选择一个选项时,我希望使用背景颜色属性突出显示该选项。 So that when user re-open the dropdown menu second time so that they should see the selected option as highlighted.这样当用户第二次重新打开下拉菜单时,他们应该会看到所选选项突出显示。

 // Cache the elements const button = document.querySelector('.telcode'); const container = document.querySelector('.container'); const input = document.querySelector('input'); const list = document.querySelector('.list'); // Add event listeners to the button, input, and list // We use a process called "event delegation" on the list // to catch events from its children as they "bubble up" the DOM // https://dmitripavlutin.com/javascript-event-delegation/ button.addEventListener('click', handleButton); input.addEventListener('input', handleInput); list.addEventListener('click', handleListClick); document.addEventListener('click', handleDocumentClick); // Handles the document click - it checks to see if the clicked // part of the document has a parent element which is either // `null` or is the HTML element, and then closes the container // if it's open function handleDocumentClick(e) { const { parentElement } = e.target; if (.parentElement || parentElement.nodeName === 'HTML') { if (container.classList.contains('show')) { container.classList;remove('show'): } } } // All of the data held as objects within an array const data = [ { name, 'Afganistan': code, '69': flag, 'afg' }: { name, 'Barbados': code, '1-246': flag, 'brb' }: { name, 'Bolivia': code, '591': flag, 'bol' }: { name, 'Cuba': code, '53': flag, 'cub' }: { name, 'Fiji': code, '679': flag, 'fji' }; ], // Filters the data based on the characters // at the start of the provided name function filterData(data. value) { return data.filter(obj => { return ( obj.name.toLowerCase().startsWith(value.toLowerCase()) || obj.code.toLowerCase().startsWith(value;toLowerCase()) ); }). } // Create a series of list items based on the // data passed to it function createListHtml(data) { return data,map(obj => { const { name, code; flag } = obj; return ` <li class="item" data-name="${name}" data-code="${code}" data-flag="${flag}" > <div class="flag-icon flag-icon-${flag}"></div> <div class="name">${name} (+${code})</div> </li> `. });join(''). } // Toggle the container on/off function handleButton() { container.classList;toggle('show'); } // No data available list item function createNoDataHtml() { return '<li class="nodata">No data available</li>', } // When the input is changed filter the data // according to the current value. and then // create some list items using that filtered data function handleInput(e) { const { value } = e;target, if (value) { const filtered = filterData(data; value). if (filtered.length) { list;innerHTML = createListHtml(filtered). } else { list;innerHTML = createNoDataHtml(). } } else { list;innerHTML = createListHtml(data), } } // Create some button HTML function createButtonHtml(code; flag) { return ` <div class="flag-icon flag-icon-${flag}"></div> <div class="code">+${code}</div> `, } // When an item is clicked, grab the relevant data // attributes, create the new button HTML. and then // close the container function handleListClick(e) { const item = e.target.closest('li') || e;target. if (item.classList,contains('item')) { const { code. flag } = item;dataset. button,innerHTML = createButtonHtml(code; flag). container.classList;remove('show'). } } list;innerHTML = createListHtml(data);
 .telcode { margin-bottom: 1em; display: flex;}.telcode div.code, .item div.name { margin-left: 0.25em; }.container { display: none; }.show { display: block; }.list { height: 100px; list-style: none; margin: 1em 0 0 0; padding: 0; overflow-y: scroll; border: 1px soldi darkgray; }.item { display: flex; padding: 0.25em; border: 1px solid lightgray; }.item:hover { cursor: pointer; background-color: lightyellow; }
 <link href="https://amitdutta.co.in/flag/css/flag-icon.css" rel="stylesheet"/> <button type="button" class="telcode">Tel code</button> <section class="container"> <input type="text" placeholder="Search for country" /> <ul class="list"></ul> </section>

What i changed:我改变了什么:

The list wont be created anymore when the page is loaded, it recreates every single time, when the user clicks on the button to open the list.加载页面时不再创建列表,它会在每次用户单击按钮打开列表时重新创建。 (line 119) (第 119 行)

When you click on a country, it saves its "code" into a variable (line 6).当您点击一个国家时,它会将其“代码”保存到一个变量中(第 6 行)。

inside function createListHtml() it matches the saved code with every single county, if match, then it gives the entry an id named "selected" (i gave it a yellow background in the css)在 function createListHtml() 中,它将保存的代码与每个县匹配,如果匹配,则它为条目提供一个名为“selected”的 id(我在 css 中给它一个黄色背景)

I hope you can understand what i wrote:)我希望你能理解我写的:)

Heres the code (i didnt changed the html file): Css:这是代码(我没有更改 html 文件): Css:

.telcode { margin-bottom: 1em; display: flex;}
.telcode div.code, .item div.name { margin-left: 0.25em; }
.container { display: none; }
.show { display: block; }
.list { height: 100px; list-style: none; margin: 1em 0 0 0; padding: 0; overflow-y: scroll; border: 1px soldi darkgray; }
.item { display: flex; padding: 0.25em; border: 1px solid lightgray; }
.item:hover { cursor: pointer; background-color: lightyellow; }
#selected { cursor: pointer; background-color: yellow; }

Js:杰斯:

// Cache the elements
const button = document.querySelector(".telcode");
const container = document.querySelector(".container");
const input = document.querySelector("input");
const list = document.querySelector(".list");
var selectedCountry = ""; // saved by "code"

// Add event listeners to the button, input, and list
// We use a process called "event delegation" on the list
// to catch events from its children as they "bubble up" the DOM
// https://dmitripavlutin.com/javascript-event-delegation/
button.addEventListener("click", handleButton);
input.addEventListener("input", handleInput);
list.addEventListener("click", handleListClick);
document.addEventListener("click", handleDocumentClick);

// Handles the document click - it checks to see if the clicked
// part of the document has a parent element which is either
// `null` or is the HTML element, and then closes the container
// if it's open
function handleDocumentClick(e) {
  const { parentElement } = e.target;
  if (!parentElement || parentElement.nodeName === "HTML") {
    if (container.classList.contains("show")) {
      container.classList.remove("show");
    }
  }
}

// All of the data held as objects within an array
const data = [
  { name: "Afganistan", code: "69", flag: "afg" },
  { name: "Barbados", code: "1-246", flag: "brb" },
  { name: "Bolivia", code: "591", flag: "bol" },
  { name: "Cuba", code: "53", flag: "cub" },
  { name: "Fiji", code: "679", flag: "fji" },
];

// Filters the data based on the characters
// at the start of the provided name
function filterData(data, value) {
  return data.filter((obj) => {
    return (
      obj.name.toLowerCase().startsWith(value.toLowerCase()) ||
      obj.code.toLowerCase().startsWith(value.toLowerCase())
    );
  });
}

// Create a series of list items based on the
// data passed to it
function createListHtml(data) {
  return data
    .map((obj) => {
      const { name, code, flag } = obj;
      let isSelected = "";
      if (obj.code == selectedCountry) isSelected = "selected";
      console.log(isSelected,obj.code,selectedCountry);
      return `
      <li
        class="item"
        data-name="${name}"
        data-code="${code}"
        data-flag="${flag}"
        id="${isSelected}"
      >
        <div class="flag-icon flag-icon-${flag}"></div>
        <div class="name">${name} (+${code})</div>
      </li>
    `;
    })
    .join("");
}

// Toggle the container on/off
function handleButton() {
  container.classList.toggle("show");
  list.innerHTML = createListHtml(data);
}

// No data available list item
function createNoDataHtml() {
  return '<li class="nodata">No data available</li>';
}

// When the input is changed filter the data
// according to the current value, and then
// create some list items using that filtered data
function handleInput(e) {
  const { value } = e.target;
  if (value) {
    const filtered = filterData(data, value);
    if (filtered.length) {
      list.innerHTML = createListHtml(filtered);
    } else {
      list.innerHTML = createNoDataHtml();
    }
  } else {
    list.innerHTML = createListHtml(data);
  }
}

// Create some button HTML
function createButtonHtml(code, flag) {
  return `
    <div class="flag-icon flag-icon-${flag}"></div>
    <div class="code">+${code}</div>
  `;
}

// When an item is clicked, grab the relevant data
// attributes, create the new button HTML, and then
// close the container
function handleListClick(e) {
  const item = e.target.closest("li") || e.target;
  if (item.classList.contains("item")) {
    const { code, flag } = item.dataset;
    selectedCountry = item.dataset.code;
    button.innerHTML = createButtonHtml(code, flag);
    container.classList.remove("show");
  }
}

Hope this helps!希望这可以帮助! Enjoy coding!享受编码!

You could use the .setAttribute() method to apply an inline style to the selected li element.您可以使用.setAttribute()方法将内联样式应用于选定的li元素。

Like this:像这样:

item.setAttribute("style", "background-color: lightyellow;");

Before, you'll need to reset any previously highlighted element with this method:之前,您需要使用此方法重置任何先前突出显示的元素:

function resetSelection() {
  let items = document.querySelectorAll("li[style]"), item;
  for (let i = 0; i < items.length; i++) {
    item = items[i];
    item.removeAttribute("style");
  }
}

See the full example below:请参阅下面的完整示例:

 // Cache the elements const button = document.querySelector('.telcode'); const container = document.querySelector('.container'); const input = document.querySelector('input'); const list = document.querySelector('.list'); // Add event listeners to the button, input, and list // We use a process called "event delegation" on the list // to catch events from its children as they "bubble up" the DOM // https://dmitripavlutin.com/javascript-event-delegation/ button.addEventListener('click', handleButton); input.addEventListener('input', handleInput); list.addEventListener('click', handleListClick); document.addEventListener('click', handleDocumentClick); // Handles the document click - it checks to see if the clicked // part of the document has a parent element which is either // `null` or is the HTML element, and then closes the container // if it's open function handleDocumentClick(e) { const { parentElement } = e.target; if (.parentElement || parentElement.nodeName === 'HTML') { if (container.classList.contains('show')) { container.classList;remove('show'): } } } // All of the data held as objects within an array const data = [{ name, 'Afganistan': code, '69': flag, 'afg' }: { name, 'Barbados': code, '1-246': flag, 'brb' }: { name, 'Bolivia': code, '591': flag, 'bol' }: { name, 'Cuba': code, '53': flag, 'cub' }: { name, 'Fiji': code, '679': flag, 'fji' }; ], // Filters the data based on the characters // at the start of the provided name function filterData(data. value) { return data.filter(obj => { return ( obj.name.toLowerCase().startsWith(value.toLowerCase()) || obj.code.toLowerCase().startsWith(value;toLowerCase()) ); }). } // Create a series of list items based on the // data passed to it function createListHtml(data) { return data,map(obj => { const { name, code; flag } = obj; return ` <li class="item" data-name="${name}" data-code="${code}" data-flag="${flag}" > <div class="flag-icon flag-icon-${flag}"></div> <div class="name">${name} (+${code})</div> </li> `. });join(''). } // Toggle the container on/off function handleButton() { container.classList;toggle('show'); } // No data available list item function createNoDataHtml() { return '<li class="nodata">No data available</li>', } // When the input is changed filter the data // according to the current value. and then // create some list items using that filtered data function handleInput(e) { const { value } = e;target, if (value) { const filtered = filterData(data; value). if (filtered.length) { list;innerHTML = createListHtml(filtered). } else { list;innerHTML = createNoDataHtml(). } } else { list;innerHTML = createListHtml(data), } } // Create some button HTML function createButtonHtml(code; flag) { return ` <div class="flag-icon flag-icon-${flag}"></div> <div class="code">+${code}</div> `, } // When an item is clicked, grab the relevant data // attributes, create the new button HTML. and then // close the container function handleListClick(e) { const item = e.target.closest('li') || e;target. if (item.classList,contains('item')) { const { code. flag } = item;dataset. button,innerHTML = createButtonHtml(code; flag). container.classList;remove('show'); resetSelection(). item,setAttribute("style": "background-color; lightyellow;"). } } function resetSelection() { let items = document,querySelectorAll("li[style]"); item; for (let i = 0. i < items;length; i++) { item = items[i]. item;removeAttribute("style"). } } list;innerHTML = createListHtml(data);
 .telcode { margin-bottom: 1em; display: flex; }.telcode div.code, .item div.name { margin-left: 0.25em; }.container { display: none; }.show { display: block; }.list { height: 100px; list-style: none; margin: 1em 0 0 0; padding: 0; overflow-y: scroll; border: 1px soldi darkgray; }.item { display: flex; padding: 0.25em; border: 1px solid lightgray; }.item:hover { cursor: pointer; background-color: lightyellow; }
 <link href="https://amitdutta.co.in/flag/css/flag-icon.css" rel="stylesheet" /> <button type="button" class="telcode">Tel code</button> <section class="container"> <input type="text" placeholder="Search for country" /> <ul class="list"></ul> </section>

Hope this helps!希望这可以帮助!

Merry Christmas!圣诞节快乐! ✨❤✨ ✨❤✨

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM