突出显示功能(mouseover / mouseout事件侦听器)无法正常工作

问题描述 投票:1回答:1

我按照一些在线说明和一些关于突出显示单词的现场推荐,但我无法得到任何展示。我还应该提一下,我没有在控制台中收到任何错误消息。

这是.js:

let createWordElems = function() {

  for (var i = 0; i <= 54; i++) {
    var singleWord = document.createElement('span') // creating 'p' element, calling it singleWord
    singleWord.innerHTML = " " + shuffledWords[i]; // setting the content of the first word

    singleWord.addEventListener("click", clickFunc);
    // set onClick event for word

    var giantArrayElement = document.querySelector('.giant-array') // selecting .giant-array and storing it in var
    giantArrayElement.appendChild(singleWord); // appending singleWord to giantArrayElement
  }
}
createWordElems();



///// ======== ////// HIGHLIGHT ///// ======== //////

function highlight() {

  var selectSpan = document.querySelector('span')

  selectSpan.addEventListener("mouseover", function(evt) {
    evt.target.style.backgroundColor = "#ebce8e";
  });

  selectSpan.addEventListener("mouseout", function(evt) {
    evt.target.style.backgroundColor = "#473611";
  });
}

highlight();

更新:

window.addEventListener('onload',function() {
function highlight() {

  var selectSpan = document.querySelector('span')

  selectSpan.addEventListener("mouseover", function(evt) {
    evt.target.style.backgroundColor = "#ebce8e";
  });

  selectSpan.addEventListener("mouseout", function(evt) {
    evt.target.style.backgroundColor = "#473611";
  });

}
highlight();

});
javascript function dom mouseover event-listener
1个回答
2
投票

.addEventListener函数通常有点棘手,因为它通常仅在元素已完全加载时才有效。要避免此问题,您应该将highlight函数放入

window.addEventListener('onload',function(){
  //your function here
}

让你的东西工作。

© www.soinside.com 2019 - 2024. All rights reserved.