Preventing image flicker on hover when replacing i

2019-07-14 19:24发布

When I hover my cursor on the logo the first time after the page loads, it starts to blink rapidly for about a second. I've thought about using sprites, but I don't want to set the logo as the background image - I already have one. Here's my CSS code:

<!DOCTYPE HTML>
<head>
<style>
html {
    background-image:url('backgroundimage.jpg');
    -webkit-background-size: 100%;
    -moz-background-size: 100%;
    -o-background-size: 100%;
    background-size: 100%;
    -webkit-filter: brightness(0.6);
    -moz-filter: brightness(0.6);
    -o-filter:  brightness(0.6);
    -ms-filter:  brightness(0.6);

}

#logo {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -250px;
    margin-left: -250px;

}

#logo:hover 
{
    content: url('logobeforehover.png');
}
</style>
</head>
<body>
    <div id="logo">
        <img src="logoafterhover.png"/>
    </div>
</body>
</html>

标签: css image hover
2条回答
叼着烟拽天下
2楼-- · 2019-07-14 20:08

There will always be some flicker, since the user's browser will have to load the image from the server. TCP & HTTP have some amount of overhead, and the fastest you can reasonably expect (even for very small images) is about 100-200ms. Which is often noticeable. In reality, the time is often higher.

Possible solutions:

  • Place the image in the page somewhere, but don't display it. Setting display: none is often used, but that doesn't seem reliable anymore; alternatively, you can add an image with a width & height of 1px and z-index of -1. IMHO this is ugly. Note that this also increases initial page load.
  • Don't use CSS, but Javascript to switch the image. This way you can pre-load the image, and change it when it's loaded & ready, for example:

    var img = new Image();
    img.onload = function() {
        $('#logo').attr('src', $(this).attr('src'));
    };
    img.src = 'example.com/image'
    
  • Use a CSS sprite, you already mentioned you don't want to do that, but I'll list it for completion's sake. IMHO, it is the best solution.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-14 20:13

Its simple... Add same Width and Height in both #logo and #logo:hover like this

 #logo {
        position: fixed;
        top: 50%;
        left: 50%;
        margin-top: -250px;
        margin-left: -250px;
        width:XXpx;
        height:XXpx;

    }

    #logo:hover 
    {
        content: url('logobeforehover.png');
        width:XXpx;
        height:XXpx;
    }
查看更多
登录 后发表回答