我有两个 HTML 文档,b.html
包含 c.html
使用 iframe
.
关于 b.html
我需要绘制一些 DIV(在我的示例中为 id=selector),它部分覆盖了 c.html
的内容在 iframe
中可视化.
我需要获取 DIV 选择器下鼠标坐标对应的 DOM 元素的 ID。
目前正在使用document.elementFromPoint()
直接在c.html
部分工作,因为当鼠标在 DIV 选择器上时我无法识别 c.html
中的底层 DOM 元素(在此示例中为 DIV c)。
我需要知道:
- 是否可以使用 document.elementFromPoint() 或任何其他方式选择另一个下的元素?
- 可能使用 DOM 和 native API 的替代解决方案是什么?
此处示例(请查看 Chrome 中的控制台):
http://jsfiddle.net/s94cnckm/5/
-------------------------------------------- b.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>B</title>
<script type="text/javascript">
window.app = {
start: function () {
}
};
</script>
<style>
#selector {
position: absolute;
top: 150px;
left: 150px;
width: 250px;
height: 250px;
-webkit-box-shadow: 0px 0px 0px 5px yellow;
-moz-box-shadow: 0px 0px 0px 5px yellow;
box-shadow: 0px 0px 0px 5px yellow;
}
#iframe {
width: 500px;
height: 500px;
border: none;
}
</style>
</head>
<body onload="app.start();">
<div id="selector">SELECTOR</div>
<iframe id="iframe" src="c.html"></iframe>
</body>
</html>
-------------------------------------------- c.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title>C</title>
<script type="text/javascript">
window.app = {
start: function () {
document.querySelector('body').addEventListener('mousemove', function (event) {
//console.log(event.pageX, event.pageY, event.target.id);
var item = document.elementFromPoint(event.pageX, event.pageY);
console.log(item.id);
}.bind(this));
}
};
</script>
<style>
body {
background-color: lightslategray;
}
#a {
position: absolute;
top: 50px;
left: 50px;
width: 100px;
height: 100px;
background-color: green;
z-index: 2;
}
#b {
position: absolute;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background-color: #ffd800;
z-index: 1;
}
</style>
</head>
<body onload="app.start();">
<h1>Content</h1>
<div id="a">a</div>
<div id="b">b</div>
</body>
</html>
最佳答案
一个可能的解决方案是使用 pointer-events
.
The CSS property pointer-events allows authors to control under what circumstances (if any) a particular graphic element can become the target of mouse events. When this property is unspecified, the same characteristics of the visiblePainted value apply to SVG content.
申请时
#selector {
/* ... */
pointer-events: none;
}
#selector
的所有内容和元素本身不再具有交互性。可能未选择内容,并且 :hover
或 click
等事件不适用。
这是带有上述 css 的演示:http://jsfiddle.net/s94cnckm/6/
关于javascript - 如何检测重叠元素下的点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29518070/