如何使 iframe 可以点击,但 iframe 的主体仍然可以点击?
我试过:
iframe.style.width = '100%'
iframe.style.height = '100%'
iframe.style.display = 'block'
iframe.style.position = 'fixed'
iframe.style.backgroundColor = 'transparent'
iframe.style.pointerEvents = 'none'
iframe.style.border = '0'
iframe.frameborder = '0'
iframe.scrolling = 'no'
iframe.allowTransparency = 'true'
在我的 I 框架中,我使用了以下 CSS:
html, body {
/* background:none transparent; */
pointer-events:auto;
}
这导致正文可见(这是我想要的),但它像 iframe 的其余部分一样是点击式的。我希望 iframe 的主体是可点击的,但实际 iframe 元素的所有其余部分都应该是可点击的。
iframe 总是比它里面的 body 大。
不幸的是,我无法从主站点访问 iframe 内容(因此无法访问 scrollHeight 等),我只能更改其实际源代码。
最佳答案
免责声明: OP 在大约两年前创建了这个问题,我的回答是在 Ian Wise 提出这个问题并对其进行详细说明之后(见评论)。
您在此处描述的内容涉及文档和子文档之间的逻辑:“如果点击事件在子文档内什么也没做,则将该点击事件应用于父文档”,因此无法处理使用 HTML/CSS。
iframe 是不同的文档。它们与其容器确实有父子关系,但 iframe 中发生的事件将由 iframe 处理。
一个需要一些代码但会起作用的想法:
- 在所有堆叠的 iframe 上方放置一个透明的 div,并捕获 点击事件位置。
- 父逻辑 ->
- 遍历现有 iframe 元素的数组。
- 发送点击位置,直到其中一个 iframe 返回肯定响应。
function clickOnCover(e, i) {
if(e && e.preventDefaule) e.preventDefault();
if(i && i >= iframes.length) {
console.log("No action.");
return;
}
var iframe = iframes[i || 0];
if(iframe.contentWindow && iframe.contentWindow.postMessage) {
iframe.contentWindow.postMessage({ x: e.clientX, y: e.clientY, i: i });
}
}
function iframeResponse(e) {
var response = e.data, iframeIndex = response.i;
if(response.success)
console.log("Action done on iframe index -> " + iframeIndex);
else
clickOnCover({ clientX: response.x, clientY: response.y }, iframeIndex+1);
}
- iFrame 逻辑 ->
- 有一个函数可以接受
clientX, clientY
并检查该位置的可能事件(可能很棘手!)。 - 如果有 Action 发生,会积极回应,反之亦然。
- 有一个函数可以接受
window.addEventListener("message", function(e) {
// Logic for checking e.x & e.y
e.success = actionExists; // Some indicator if an action occurred.
if(window.parent && window.parent.postMessage) {
window.parent.postMessage(e);
}
});
此解决方案在父文档中继续管理事件,只需要遍历任意数量的堆叠 iframe。
找到一个相关的 SO 问题来进一步支持我的主张:Detect Click in Iframe
关于javascript - 让 iframe 点击,但不是 iframe 的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766035/