AddEventListener和鼠标悬停以隐藏段落

时间:2019-05-05 22:51:21

标签: javascript addeventlistener

我试图了解addEventListener,并在有人将鼠标悬停在按钮上时使用鼠标悬停功能隐藏段落。我在chrome开发人员中未收到任何错误,因此我不确定自己缺少什么。我想念什么?

document.addEventListener("mouseover", myFunction);
document.addEventListener("mouseover", myThirdFunction);

function myFunction() {
  document.getElementById("sun").style.visibility = "hidden";
}

function myThirdFunction() {
  document.getElementById("sun").style.visibility = "visible";
}
<!-- You should:1. Rover over the below button and make the paragraph below 
    it disappear. -->
<input type="button" value="Roll Over Me" class="rollOverMe" />
<p id="sun"> This paragraph will burn from the heat of the sun!</p>

我希望每当用户将鼠标悬停在按钮上时,p id =“ sun”都不可见。

2 个答案:

答案 0 :(得分:2)

  1. 不要在页面中重复太多document.getElementByIds。对于小型应用程序来说,可以练习和学习。来自DOM的引用/选择过多会降低性能。

  2. 如前所述,尝试给出有意义的函数名称。

  3. 有多个鼠标事件侦听器。为了实现您的期望,我们需要同时使用mouseleave和mouseover。

var buttonElement = document.getElementById("tooltip-btn");
var paragraph = document.getElementById("sun");

function myFunction() {
  paragraph.style.visibility = "hidden";
}

function myThirdFunction() {
  paragraph.style.visibility = "visible";
}

buttonElement.addEventListener("mouseover", myFunction);
buttonElement.addEventListener("mouseleave", myThirdFunction);
<input id="tooltip-btn" type="button" value="Roll Over Me" class="rollOverMe" />
<p id="sun"> This paragraph will burn from the heat of the sun!</p>

答案 1 :(得分:0)

一个非常简单的问题,在您开始时,希望对您有所帮助。

就我个人而言,我将停止使用W3School并开始使用MDN。 MDN Tutorials是一个好的开始。

关于您的问题,有一点点错误。以下内容是许多常见情况的基本结构。

function paraHide(e) {
  var d = document.getElementById("sun");
  d.style.visibility = "hidden";
}
function paraShow(e) {
  var d = document.getElementById("sun");
  d.style.visibility = "visible";
}
/*
  window.onload means wait until the HTML has loaded, then
  automatically start the following JavaScript
*/
window.onload = function() {
  // get all elements with the class "rollOverMe"
  var d = document.querySelectorAll(".rollOverMe");
  // if any elements found, continue
  if (d) {
    var i, max = d.length;
    // for each found element, add the following
    // Event Lsiteners
    for(i=0;i<max;i++) {
      d[i].addEventListener("mouseover",paraHide,false)
      d[i].addEventListener("mouseout",paraShow,false)
    }
  }
}
<input type="button" value="Roll Over Me" class="rollOverMe" />
<p id="sun"> This paragraph will burn from the heat of the sun!</p>
<input type="button" value="Over me too!" class="rollOverMe" />