使用jquery与另一个交换时,图像闪烁

时间:2013-12-19 16:48:01

标签: jquery html css image

我有两张图片,我想在页面加载时另外显示。以下是我想要的jsfiddle链接:

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:

$(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张图片是1)solarpanel.png和2)solarpanelshine.png

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

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

2 个答案:

答案 0 :(得分:2)

只有在页面上呈现CSS图像时才会下载它们,因此在您第一次更改类之前,不会下载第二个图像。我会将它们切割成一个图像并切换背景位置而不是背景图像URL。这种技术称为CSS Sprites,是性能的良好实践,值得尝试:

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

答案 1 :(得分: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