CSS :hover 仅在鼠标移动时有效

2022-01-22 00:00:00 hover javascript css styles

我创建了一个非常基本的示例:

I created a very basic sample:

HTML

<div id="bla"></div>

CSS

#bla {
    width:400px;
    height:400px;
    background-color:green;
    display:none;
}

#bla:hover{
   background-color:red;
}

如您所见,它是一个最初隐藏的 DIV,当鼠标悬停在它上面时会改变颜色.

As you can see it's a DIV that is initially hidden and changes color when mouse hovers over it.

此 JavaScript 在 2 秒后将其取消隐藏

This JavaScript unhides it after 2 seconds

setTimeout(function() {
     document.getElementById('bla').style.display="block";
},2000)

但是,如果您将鼠标放在 DIV 即将出现的位置上 - 当它出现时 - 它会以未悬停状态出现.只有当您实际移动鼠标时才会发生悬停效果.

But if you place your mouse over location where the DIV is about to appear - when it appears - it appears in unhovered state. Only when you actually move the mouse - hover effect takes place.

这是一个演示.运行它并立即将鼠标放在结果窗格上.

Here's a demo. Run it and immediately place mouse over result pane.

这是设计使然吗?有没有办法(最好不使用 JS)来检测 DIV 悬停?

Is this by design? Is there a way (without JS preferable) to detect that DIV is hovered?

推荐答案

虽然你可以使用 opacity,@BrianPhillips 提到,但它在 IE 8 中不起作用.我不知道纯 CSS 解决方案,但这里有一个足够简洁的 Javascript 解决方法:

While you can use opacity, @BrianPhillips mentioned, it doesn't work in IE 8. I don't know of a pure CSS solution, but here's a concise enough Javascript workaround:

window.onmousemove=function(event){
    ev = event || window.event;
    if (event.pageX <= 400 && event.pageY <= 400){
        document.getElementById('bla').style.backgroundColor= "red";
    } else {
        document.getElementById('bla').style.backgroundColor= "green";
    }
}
setTimeout(function() {
     document.getElementById('bla').style.display="block";
},2000)

演示

相关文章