Onmouseout在将鼠标移动到某些元素时不能运行?

时间:2016-12-04 19:39:01

标签: javascript html

因此,当您将鼠标悬停在article元素上时,此代码会播放音频剪辑。问题是当鼠标悬停在子元素上时它会停止。当鼠标悬停在常规article元素和子元素上时,如何使Stopsound函数不运行?

编辑:基本上我不想在交替使用哪个子元素时运行这两个函数。



   function PlaySound(soundobj) {
     var thissound = document.getElementById(soundobj);
     thissound.play();
   }

   function StopSound(soundobj) {
     var thissound = document.getElementById(soundobj);
     thissound.pause();
     thissound.currentTime = 0;
   }

* {
  margin: 0;
  padding: 0;
}
article24 {
  width: 50px;
  height: 100px;
  background-color: green;
}
#box24 {
  width: 50px;
  height: 50px;
  background-color: blue;
}
#present24 {
  width: 50px;
  height: 50px;
  background-color: red;
}
#bauble24 {
  width: 10px;
  height: 10px;
}

<audio id='mySound' src="http://www.freesound.org/data/previews/278/278903_3546642-lq.mp3"></audio>
<article id="article24" onmouseover="PlaySound('mySound')" onmouseout="StopSound('mySound')">
  <div id="box24">
    <h2></h2>
  </div>
  <div id="present24">
    <a href="">
      <div id="bauble24">
        <p id="belle24">""</p>
      </div>
    </a>
  </div>
</article>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

实际上,只要鼠标悬停在另一个元素上,mouseout事件就会触发,即使该元素是事件目标元素的子元素。

但是,当您保持在父元素的范围内时,mouseover事件将触发 ,因此如果您在处理mouseout事件之前可以检测到该事件,你可以区分这种情况和父元素的真实离开。

这可以通过延迟setTimeout治疗来实现,并在您立即跟踪mouseover事件后取消该操作:

var timer = -1; // ID of a timer we will use

function PlaySound(soundobj) {
    clearTimeout(timer); // cancel any pending StopSound action
    var thissound=document.getElementById(soundobj);
    thissound.play();
}

function StopSound(soundobj) {
    timer = setTimeout(function () { // defer the action
        var thissound=document.getElementById(soundobj);
        thissound.pause();
        thissound.currentTime = 0;
   }, 0); // 0 is enough, as the `mouseover` event is already posted in the message queue
}