鼠标悬停事件在跟随鼠标移动的div上不起作用

3

我有一个名为 hoverZone 的 div,还有另一个名为 followMouse 的 div。如其名,followMouse div 一直跟随着鼠标移动,但问题在于我的 CSS 中有一条规则从未被应用:

.hoverZone:hover ~ .followMouse {
box-shadow: 0px 0px 30px #fff;
}

有什么办法可以解决这个问题吗?

window.addEventListener("mousemove", move, false);

function move(e){
    var mouseX = parseInt(e.clientX);
    var mouseY = parseInt(e.clientY);
     
    var follower = document.querySelector(".followMouse");
    follower.style.left = mouseX + "px";
    follower.style.top = mouseY + "px";
}
.hoverZone {
    display: block;
    height: 90px;
    width: 90px;
    position: absolute;
}

.hoverZone:hover ~ .followMouse {
    background-color: blue;
    box-shadow: 0px 0px 30px #fff;
}

.followMouse{
    width: 90px;
    height: 90px;
    background-color: orange;
}
<div class="hoverZone"></div>
<div class="followMouse"></div>

1个回答

2

.followMouse 默认情况下具有 position:static;,因此更改 topleft 等对元素没有任何影响。将 position: absolute; 赋予 .followMouse 将解决您的问题。

window.addEventListener("mousemove", move, false);

function move(e){
    var mouseX = parseInt(e.clientX);
    var mouseY = parseInt(e.clientY);
     
    var follower = document.querySelector(".followMouse");
    follower.style.left = mouseX + "px";
    follower.style.top = mouseY + "px";
}
.hoverZone {
    display: block;
    height: 90px;
    width: 90px;
    position: absolute;
}

.hoverZone:hover ~ .followMouse {
    background-color: blue;
    box-shadow: 0px 0px 30px #000;
}

.followMouse{
    width: 90px;
    height: 90px;
    background-color: orange;
    position:fixed;
}
<div class="hoverZone"></div>
<div class="followMouse"></div>


你好!谢谢你的回答,我忘记在上面的代码中加入了 followMouse 的位置是固定的 (position: fixed;),但为什么它必须是绝对定位? - Safirah
无论如何,您都可以使用“position:fixed”。 - Alex
1
你可以给 followMouse 类 CSS 规则 pointer-events: none,以防止它从 hoverZone 中夺取事件。 - Omri Luzon
1
@OmriLuzon 谢谢,就这样! - Safirah
1
@Safirah 我将 position 更改为 fixed,然后要从 .followMouse 中删除 event-pointer,您可以使用 Omir 的评论。 - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接