是否可以在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结合使用。在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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句