CSS :hover works only when mouse moves

前端 未结 3 1510
粉色の甜心
粉色の甜心 2021-01-04 08:39

I created a very basic sample:

HTML

CSS

#bla {         


        
相关标签:
3条回答
  • 2021-01-04 08:49

    When you set display to none the image takes up no space meaining there is nowhere to hover over.

    I would set the background-image in you css to rgba(0 0 0 0); making it invisible but still in the dom. You can then change your javascript to

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

    http://jsfiddle.net/euT7k/3

    0 讨论(0)
  • 2021-01-04 09:00

    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)
    

    Demo

    0 讨论(0)
  • 2021-01-04 09:11

    You could try using CSS opacity along with setting it to position: absolute to prevent it from taking up flow on the page. This appears to work properly:

    CSS:

    #bla {
        width:400px;
        height:400px;
        background-color:green;
        opacity: 0;
        position: absolute;
    }
    

    JS:

    setTimeout(function() {
             document.getElementById('bla').style.opacity="1";
             document.getElementById('bla').style.position="relative";
    },2000)
    

    Demo

    The key here is that elements with opacity respond to events (click, hover, etc), while elements with visibility: hidden and display:none do not. (source)

    Note that opacity isn't available in IE 8 and below.

    0 讨论(0)
提交回复
热议问题