javascript - 无法使用 javascript 代码将 css 类设置为 HTML 元素

标签 javascript html css vue.js

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

1 - Dropdown appears in front of the top NAV elements but behind the main content elements: I have tried to force the code with z-index on the browser dev tool but it completely ignores it.
enter image description here

2 - it seems like some classes .autocomplete-items are set by code.

enter image description here

我的代码:

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示例 enter link description here

最佳答案

发生这种情况可能是因为您没有关闭 .autocomplete 的大括号

.autocomplete
  { 
  position: relative;
  display: inline-block; 
  width: 60%; 
  margin: auto auto; 
                          // here is the missing bracket
.autocomplete-items {

关于javascript - 无法使用 javascript 代码将 css 类设置为 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66851916/

相关文章:

javascript - 创建 Microsoft.Maps.Search.Address 的实例

javascript - 使用 jQuery 在 div 之间导航

javascript - 范围 0-100 使用 jQuery inputmask 插件

html - 如何从ios中的工具栏删除边框?

带有 Bootstrap 的 html 和 css : grid structure does not align

javascript - 如何使弹出式 div 在单击时隐藏/显示

javascript - Jquery 在悬停时更改图像并在鼠标悬停时设置默认图像

html - 如何将子列表项设置为与 css 中的父列表项不同的高度?

html - 是否可以使 Html 表格的高度独立于其他表格?

jquery - 使用 SlideToggle 展开 div