首页 > 解决方案 > 无法使用 javascript 代码将 css 类设置为 HTML 元素

问题描述

我创建了一个“自动完成下拉菜单”,在触发输入事件时附加到容器中。触发器工作得很好。但是注意到 CSS 类未设置为容器元素。Chrome tool dev 我看不到由代码设置的 CSS 类。这是一个 VUE jS 应用程序,函数在mount()钩子中调用。我面临两个问题:

1 - 下拉列表出现在顶部 NAV 元素的前面,但在主要内容元素的后面:我试图在浏览器开发工具上强制使用 z-index 代码,但它完全忽略了它。
在此处输入图像描述

2 - 似乎某些类.autocomplete-items是由代码设置的。

在此处输入图像描述

我的代码:

HTML

    <div class="autocomplete">
        <input id="myInput" v-model="currentInput" @keypress.space="saveChip" @keydown.delete="backspaceDelete" @keypress.enter="clear"
        type="text" name="myCountry" placeholder="Country">
      </div>

JS

function autocomplete(inp, arr) { 
      console.log('autocomplete -START')
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus; 
      
    

  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) { 

      console.log('inp.addEventListener("input", function(e) -START')

      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.appendChild(a);
      /*for each item in the array...*/
      for (i = 0; i < arr.length; i++) {
      var pos = arr[i].toUpperCase().indexOf(val.toUpperCase());
        /*check if the item starts with the same letters as the text field value:*/
        if (pos > -1) {
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
          b.innerHTML = arr[i].substr(0, pos);
          b.innerHTML += "<strong>" + arr[i].substr(pos, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(pos + val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*execute a function when someone clicks on the item value (DIV element):*/
          b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) { 
      console.log(' inp.addEventListener("keydown"')

      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
      } 
      console.log(' inp.addEventListener("keydown" -END')

  });
  function addActive(x) {
      console.log('addActive -START')

    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active"); 
     
      console.log('addActive -END')

  }
  function removeActive(x) { 
      console.log('removeActive -START')

    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    } 
      console.log('removeActive -END')

  }
  function closeAllLists(elmnt) { 
      console.log('closeAllLists -START')

    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
        x[i].parentNode.removeChild(x[i]);
      }
    } 
      console.log('closeAllLists -END')

  }
  /*execute a function when someone clicks in the document:*/
  document.addEventListener("click", function (e) {
      closeAllLists(e.target);
  });
},
}, 
   mounted()
  {
       this.autocomplete(document.getElementById("myInput"), this.countries); 
  },

CSS

.autocomplete
  { 
  position: relative;
  display: inline-block; 
  width: 60%; 
  margin: auto auto; 

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 10000; 
  background-color: turquoise;
  /*position the autocomplete items to be the same width as the container:*/
  top: 100%;
  left: 0;
  right: 0;
}

.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff; 
  border-bottom: 1px solid #d4d4d4; 
}

/*when hovering an item:*/
.autocomplete-items div:hover {
  background-color: #e9e9e9; 
}

/*when navigating through the items using the arrow keys:*/
.autocomplete-active {
  background-color: DodgerBlue !important; 
  color: #ffffff; 
} 
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px; 
  width: 100%; 
  margin: auto;
  border-radius: 3px;
}
  }  
 

这是 codepen 上的 SRC 示例 在此处 输入链接描述

标签: javascripthtmlcssvue.js

解决方案


If you use scss, your css code format is correct. if not, you need to check your css again. for this, please check the above answer of @biberman.

From your attached screenshot, I can recognize there is an index issue in your css.

Please add z-index as 1000 or bigger for .autocomplete

and please set background for .autocomplete

.autocomplete
  { 
   position: relative;
   display: inline-block; 
   width: 60%; 
   margin: auto auto; 
   background-color: #fff;
   z-index: 1000
 }

推荐阅读