如何在 INSIDE 中包含<div>'mousemove'效果



当我添加鼠标移动事件我得到它在我的整个页面。我希望它只在div中。当我的光标离开div时,它不应该显示我添加的效果。请帮我解决这个问题。谢谢

截图说明

六边形图像-如果你想尝试

下面是我的代码(包括HTML, CSS和JS)

const BG = document.querySelector(".bg");
document.querySelector(".container").addEventListener("mousemove", function(e) {
BG.style.left = e.clientX + "px";
BG.style.top = e.clientY + "px";
});
.container {
height: 800px;
width: 100%;
background-color: #000;
position: relative;
}
.hex {
background: url("images/Hexagon.svg") repeat;
height: 800px;
width: 100%;
position: absolute;
background-size: 500px;
z-index: 1;
}
.bg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 300px;
width: 300px;
background: linear-gradient(90deg, #335bfa 0%, #2ae9c9 100%);
filter: blur(20px);
z-index: 0;
overflow: none;
}
<body>
<div class="container">
<div class="hex"></div>
<div class="bg"></div>
</div>
<script src="index.js"></script>
</body>

添加overflow: hidden;到您的。container

overflow: hidden放入.container

const BG = document.querySelector(".bg");
document.querySelector(".container").addEventListener("mousemove", function(e) {
BG.style.left = e.clientX + "px";
BG.style.top = e.clientY + "px";
});
.container {
height: 800px;
width: 100%;
background-color: #000;
position: relative;
overflow: hidden; 
}
.hex {
background: url("images/Hexagon.svg") repeat;
height: 800px;
width: 100%;
position: absolute;
background-size: 500px;
z-index: 1;
}
.bg {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 300px;
width: 300px;
background: linear-gradient(90deg, #335bfa 0%, #2ae9c9 100%);
filter: blur(20px);
z-index: 0;
overflow: none;
}
<body>
<div class="container">
<div class="hex"></div>
<div class="bg"></div>
</div>
<script src="index.js"></script>
</body>

可以在.bg元素上使用pointer-events: none;,如下面的演示所示。这就是为什么您的代码没有按预期工作的原因,因为div.container中的.bg元素正在向父元素冒泡事件。要防止这种情况发生,最快捷的方法就是完全避免使用该元素来捕获事件。

const BG = document.querySelector(".bg");
document.querySelector(".container").addEventListener("mousemove", function(e) {
BG.style.left = e.clientX + "px";
BG.style.top = e.clientY + "px";
});
.container {
height: 800px;
width: 100%;
background-color: #000;
position: relative;
}
.hex {
background: url("images/Hexagon.svg") repeat;
height: 800px;
width: 100%;
position: absolute;
background-size: 500px;
z-index: 1;
}
.bg {
pointer-events: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 300px;
width: 300px;
background: linear-gradient(90deg, #335bfa 0%, #2ae9c9 100%);
filter: blur(20px);
z-index: 0;
overflow: none;
}
<body>
<div class="container">   
<div class="hex"></div>
<div class="bg"></div>
</div>

<script src="index.js"></script>
</body>

最新更新