是否可以检测 HTML 中另一个元素下相邻(不是其子级)的对象上的鼠标事件?
例如:
<style>
#test, test2 {
width: 100%;
height: 100%
}
</style>
<html>
<section class="full" id="test">
Full Screen
</section>
<section class="anotherFull" id="test2">
Full Screen As well
</section>
<script>
var elem = document.querySelector('#test2');
elem.addEventListener('hover', function(){
alert('you are hovering');
}, false);
</script>
<html>
如果我在页面上方,无论我使用 mouseenter
mouseover
还是 hover
,也无论我在页面中向下看多远e
(来自 document.addEventListener('hover', function(e){}, false)
; (如 e.target
等。我无法检测到第二个(相邻)元素上的悬停。
最佳答案
解决这个问题的一种方法是简单地链接事件。您可以结合使用addEventListener 和dispatchEvent 来完成此操作。一篇名为 Creating and triggering events 的 MDN 文章对此进行了概述。
var
outer = document.getElementById("outer"),
inner = document.getElementById("inner")
;
inner.addEventListener('mouseenter',function(e){
alert('hovering inner');
},false);
outer.addEventListener('mouseenter',function(ev){
alert('hovering outer');
this.style.display = "none";
var tar = document.elementFromPoint(ev.clientX, ev.clientY);
this.style.display = "block";
tar.dispatchEvent(new Event('mouseenter'));
},false);
#screen{
position:relative;
width:50px;
height:50px;
}
#outer{
position:absolute;
top:0;
left:0;
z-index:2;
width:50px;
height:50px;
background-color:blue;
}
#inner{
position:absolute;
top:0;
left:0;
z-index:1;
width:50px;
height:50px;
background-color:red;
}
<fieldset>
<legend>Screen Mockup</legend>
<div id="screen">
<div id="outer"></div>
<div id="inner"></div>
</div>
</fieldset>
关于javascript - 如何检测 HTML 中被覆盖的相邻元素上的鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27868330/