2013-12-19 19 views
0

我有2个图像,我想要显示在页面加载替代。下面是的jsfiddle链接,我想要的东西:使用图像闪烁,而用另一个交换使用jquery

$(window).load(function() { 
    HomePageAnimation.panelShine(); 
}); 

var HomePageAnimation = { 
    panelShine: function(){ 
     var index, timesRun, interval,solarPanel; 
     index =0; 
     timesRun = 0; 
     solarPanel = $("span.solar-panel"); 
     interval = setInterval(function(){ 
      timesRun += 1; 
      if(timesRun === 8){ 
       clearInterval(interval); 
      } 
      switch(index){ 
       case 0: 
        solarPanel.addClass("solar-panel-grey"); 
        index = 1; 
        break; 
       case 1: 
        solarPanel.removeClass("solar-panel-grey"); 
        index = 0; 
        break; 
      } 
     },600);  
    } 

}; 

2幅图像:

http://jsfiddle.net/8mMZn/

HTML:

<span class="solar-panel" title="Solar Panel"></span> 

CSS:

.solar-panel {position:absolute; left:280px; width:103px; height:83px;background:url(http://s28.postimg.org/q0ukhrf5l/solarpanel.png) no-repeat; } 
span.solar-panel-grey {background:url(http://s16.postimg.org/5kik3yfm9/solarpanelshine.png) no-repeat;} 

JS是1) solarpanel.png和2)solarpanelshine.png

正在显示页面加载“solarpanel”。当您第一次运行该页面时,您会看到第一个图像“solarpanel”消失/闪烁一次,然后图像交换动画正常工作。 当你再次运行这个页面时,它会工作得很好。如果清除缓存(使用chrome - Ctrl + F5)并再次运行,则第一个图像将再次消失/闪烁。 我该如何避免这种情况?

而这只发生在图像从服务器提供时,它不发生在本地。

+2

您可以通过预加载这两个图像,以便通过交换发生时,图像已经加载避免它。 –

+0

你可以给我一些关于如何做到这一点的指针吗?另外,只是好奇它为什么会发生。第一张图片“solarpanel”已经存在于页面上,而js代码所做的只是在另一张图片上覆盖它,并在几个周期内删除相同的图片。那么,为什么第一个图像甚至在所谓的动画之前消失/闪烁。任何想法? – whyAto8

+0

什么动画? –

回答

2

只有在页面上呈现CSS图像时,才会下载CSS图像,所以在第一次更改课程之前,不会下载第二张图像。我会将它们剪切成一张图片并切换背景位置而不是背景图片网址。该技术被称为CSS精灵,是表现很好的做法,所以值得尝试:

http://css-tricks.com/css-sprites/

+0

谢谢大家,我会把它变成一个精灵,我相信它只是在凯文在我的帖子的回应中建议的那种预加载。 – whyAto8

+0

现在完美运作。 :-) – whyAto8

+0

很高兴听到它:) – thebiffboff

2

你需要预加载你的形象,因此不会闪烁。

http://jsfiddle.net/8mMZn/10/

$.fn.preload = function() { 
    this.each(function(){ 
     $('<img/>')[0].src = this; 
     console.log(this.src); 
    }); 
} 

$(window).load(function() { 
    $(['http://s28.postimg.org/q0ukhrf5l/solarpanel.png','http://s16.postimg.org/5kik3yfm9/solarpanelshine.png']).preload(); 
HomePageAnimation.panelShine(); 
//rest of code 
+0

感谢迈克,我明白了。然而,我发现精灵解决方案更加简单和干净,所以我实现了这一点,尽管两种解决方案都有相同的用途。 – whyAto8