简体   繁体   English

悬停时背景变化闪烁

[英]Background change blinks on hover

Here, I have a site I'm coding www.startingcanvas.com , I added some backgrounds to the icons you will se there, on hover of an icon, the background behind them changes. 在这里,我有一个网站正在编码www.startingcanvas.com ,我在图标上添加了一些背景,将鼠标悬停在图标上时,它们后面的背景也会更改。

The problem is that on first hover on each icon, the background blinks. 问题在于,在第一次将鼠标悬停在每个图标上时,背景会闪烁。 I thought it was because the images were loading. 我以为是因为图像正在加载。

But I tried a couple of methods to preload image: 但是我尝试了几种方法来预加载图像:

Put them in a display:none div: 将它们放在显示中:none div:

<div style="display:none">
   <img src="images/myimage1.jpg" />
   <img src="images/myimage2.jpg" />
   <!-- etc... -->
</div>

And the one with javascript: 和一个与JavaScript:

for(var i = 0; i < to.icons.length; i++){
    new Image().src = to.icons[i].bg;
    //console.log(to.icons[i].bg);
}

Without solution, do have any ideas, here is my javascript code: 没有解决方案,有任何想法,这是我的JavaScript代码:

$('.bussiness-icons li').hover(function(){
    var id = $(this).data('id');
    var bg = $('#' + id).attr('src');

    $('.icon-templates').css('background', 'url(' + bg +')');
}, function(){
    return;
});

You should make a CSS sprite image that contains all the images and there hover states. 您应该制作一个包含所有图像并具有悬停状态的CSS Sprite图像。 For example if your icons where 50x50px and we placed the 'hover' icon directly below it - then in our css on the :hover of the element we just 'push' the background position to show the 'hover' img. 例如,如果您的图标的位置为50x50px,并且我们将“悬停”图标直接放置在其下方-那么在元素的:hover的CSS中,我们只是“推”背景位置以显示“悬停” img。

#icon-one {
  background: url('<Sprite url>'); 
}

#icon-one:hover {
  background-position: <x position>0px <y position>-50px;
}

This also saves on http requests if you bundle all your images in one file! 如果将所有图像捆绑在一个文件中,这也可以节省http请求! Chris Coyier did an article before on CSS Sprites: http://css-tricks.com/css-sprites/ 克里斯·科耶尔(Chris Coyier)之前在CSS Sprites上发表了一篇文章: http : //css-tricks.com/css-sprites/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM