多个绝对元素的事件捕获
event capture by multiple absolute elements
我有多个 div 接收鼠标事件,如下所示,div 在某些区域重叠。如果鼠标指针在重叠区域上,我需要触发两个事件(即打印蓝色和红色),目前它只打印红色。
<div style="border: solid 1px blue;width:100px;height:100px;
position:absolute;top: 50px;left:50px;"
onMouseMove="console.log('blue');">
</div>
<div style="border: solid 1px red;width:100px;height:100px;
position:absolute;top: 20px;left:20px;"
onMouseMove="console.log('red');">
</div>
你绝对可以尝试这样的事情。
function checkOverlap(object) {
var div1 = document.getElementById("myDiv1");
//positions of div1
var rect1 = div1.getBoundingClientRect();
var div2 = document.getElementById("myDiv2");
var rect2 = div2.getBoundingClientRect();
//X and Y co-ordinate of mouse
var x = event.clientX;
var y = event.clientY;
if ((x > rect2.left) && (y > rect2.top)) {
console.log('happy');
}
}
<div id="myDiv2" style="border: solid 1px blue;width:100px;height:100px;
position:absolute;top: 50px;left:50px;">
</div>
<div id="myDiv1" style="border: solid 1px red;width:100px;height:100px;
position:absolute;top: 20px;left:20px; z-index: 1;" onMouseMove="checkOverlap();">
</div>
如果您只将鼠标悬停在重叠部分,将在此处打印“happy”。
我有多个 div 接收鼠标事件,如下所示,div 在某些区域重叠。如果鼠标指针在重叠区域上,我需要触发两个事件(即打印蓝色和红色),目前它只打印红色。
<div style="border: solid 1px blue;width:100px;height:100px;
position:absolute;top: 50px;left:50px;"
onMouseMove="console.log('blue');">
</div>
<div style="border: solid 1px red;width:100px;height:100px;
position:absolute;top: 20px;left:20px;"
onMouseMove="console.log('red');">
</div>
你绝对可以尝试这样的事情。
function checkOverlap(object) {
var div1 = document.getElementById("myDiv1");
//positions of div1
var rect1 = div1.getBoundingClientRect();
var div2 = document.getElementById("myDiv2");
var rect2 = div2.getBoundingClientRect();
//X and Y co-ordinate of mouse
var x = event.clientX;
var y = event.clientY;
if ((x > rect2.left) && (y > rect2.top)) {
console.log('happy');
}
}
<div id="myDiv2" style="border: solid 1px blue;width:100px;height:100px;
position:absolute;top: 50px;left:50px;">
</div>
<div id="myDiv1" style="border: solid 1px red;width:100px;height:100px;
position:absolute;top: 20px;left:20px; z-index: 1;" onMouseMove="checkOverlap();">
</div>
如果您只将鼠标悬停在重叠部分,将在此处打印“happy”。