我在网页中嵌入了多个 iframe。在父页面上滚动时,一旦鼠标光标位于其上,滚动就会停止并开始转发到 iframe。我知道我可以使用
pointer-events: none
禁用 iframe 上的指针事件,但我需要 iframe 允许单击,同时忽略滚动。
我可以控制父页面和 iframe 内容。有没有办法解决这个问题,如何使用 iframe、CSS 或 JavaScript 上的 HTML 属性来解决这个问题?
你可以做这样的事情:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parent Page</title>
<style>
.iframe-container {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.iframe-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border: none;
}
</style>
</head>
<body>
<!-- Parent Page Content -->
<div class="iframe-container">
<iframe src="iframe.html" id="iframe"></iframe>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var iframe = document.getElementById('iframe');
// Event listener for scrolling on the parent page
window.addEventListener('scroll', function(event) {
// Check if the mouse is over the iframe
if (!isMouseOverIframe(event.clientX, event.clientY)) {
// Allow scrolling on the parent page
event.stopPropagation();
}
});
// Function to check if the mouse is over the iframe
function isMouseOverIframe(x, y) {
var rect = iframe.getBoundingClientRect();
return (
x >= rect.left &&
x <= rect.right &&
y >= rect.top &&
y <= rect.bottom
);
}
});
</script>
</body>
</html>