问题描述
我的标记完全按照以下顺序:
<iframeContainer>
<iframe>
</iframeContainer>
<container>
<button1>
<button2>
<sidebar>
...
</container>
container
应该位于iframe本身的上方。不幸的是,由于container
的w / h为100%,这使我的游戏无法正常运行,并且这显然不允许点击iframe本身。示例:
const buttonThatIWannaClick = document.getElementById('buttonOverIframe');
buttonThatIWannaClick.addEventListener('click',function() {
console.log('I am able to click the button!');
});
#videoContainer {
position: absolute;
z-index: 9998;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
#buttonOverIframe {
position: absolute;
color: white;
top: 50%;
left: 50%;
}
#videoContainer iframe {
width: 100%;
height: 100%;
}
#container {
display: flex;
position: absolute;
z-index: 9998;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
#openSidebar {
display: flex;
position: absolute;
z-index: 1;
top: 50%;
left: 30px;
color: white;
transform: translate3d(0,50%,0);
}
<div id="videoContainer">
<div id="buttonOverIframe">Button Inside Iframe</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/5qap5aO4i9A" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div id="container">
<div id="openSidebar">Open Sidebar</div>
</div>
您可以看到我无法与iframe进行交互。 **我知道这是因为container
的宽度/高度为100%,即使肉眼看不见,浏览器也会将其视为在前面。
我该如何重新排列以下内容:
- 我可以与iframe上的按钮进行交互。
- 我可以检测到iframe外部或其上的点击吗?
解决方法
使用pointer-events: none;
容器和pointer-events: initial
封装活动元素
const buttonThatIWannaClick = document.getElementById('buttonOverIframe');
buttonThatIWannaClick.addEventListener('click',function() {
alert('I am able to click the button!');
});
#videoContainer {
position: absolute;
z-index: 9998;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
#buttonOverIframe {
position: absolute;
color: white;
top: 50%;
left: 50%;
}
#videoContainer iframe {
width: 100%;
height: 100%;
}
#container {
display: flex;
position: absolute;
z-index: 9998;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
}
#openSidebar {
display: flex;
pointer-events: initial;
position: absolute;
z-index: 1;
top: 50%;
left: 30px;
color: white;
transform: translate3d(0,50%,0);
}
<div id="videoContainer">
<div id="buttonOverIframe">Button Over Iframe</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/5qap5aO4i9A" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<div id="container">
<div id="openSidebar">Open Sidebar</div>
</div>