JavaScript中的mouseenter和mouseleave不起作用

时间:2016-02-02 11:43:44

标签: javascript jquery

我在javascript中遇到了mouseenter和mouseleave事件的问题。奇怪的是,如果用click或dblclick事件替换这两个事件,代码就可以工作。希望你能在这里帮助我。 PS:我正在使用铬。 不知道如何让js在小提琴上工作......现在

这是代码:

https://jsfiddle.net/frempong69/t7du0kte/

(function() {
  window.onload = function() {
    var box = document.getElementsByClassName("box")[0];

    var change = function() {
      box.style.backgroundColor = "green";
    };

    var normal = function() {
      box.style.backgroundColor = "blue";
    }

    addEventListener("click", change, false);
    addEventListener("mouseleave", normal, false);
  };

}());

4 个答案:

答案 0 :(得分:2)

您正在向window对象添加mouseleave / mouseenter处理程序。 click处理程序有效,因为它会向窗口对象冒泡,但mouseentermouseleave事件不会冒泡,因此附加到窗口对象的侦听器不会被触发

您需要将listerns添加到box元素

(function() {
  window.onload = function() {
    var box = document.getElementsByClassName("box")[0];

    var change = function() {
      box.style.backgroundColor = "green";
    };

    var normal = function() {
      box.style.backgroundColor = "blue";
    }

    box.addEventListener("mouseenter", change, false);
    box.addEventListener("mouseleave", normal, false);
  };


}());
.box {
  background-color: red;
  width: 400px;
  height: 200px;
  margin: 50px auto;
  position: relative;
}
.box:after {
  content: " ";
  width: 0px;
  height: 0px;
  border-top: 100px solid transparent;
  border-right: 100px solid transparent;
  border-bottom: 100px solid transparent;
  border-left: 100px solid red;
  position: absolute;
  left: 100%;
  top: 50%;
  margin-top: -100px
}
<div class="box">
</div>

答案 1 :(得分:0)

你可以这样做

 box.onmouseenter = change;
 box.mouseleave = normal;

答案 2 :(得分:0)

你必须改变

box.addEventListener("click", change, false);
box.addEventListener("mouseout", normal, false);

用这个

  <asp:CheckBox ID="ChkLeads" runat="server" 
            Checked='<%#bool.Parse(Eval("columnName").ToString())%>' />

答案 3 :(得分:0)

你只需使用这个

<div class="box" onmouseover="style.background='green'" onmouseout="style.background='red'">
</div>

它的工作

相关问题