8

我正在尝试消除 Chrome 和 FF 中的闪烁,尽管它在 FF 中要少得多。该脚本根据水平鼠标位置滚动 20 个背景 jpg。这种工作但非常闪烁。

jQuery

$( document ).ready( function() {
var xSlider = $("#third"); //cache
var loopvar = 10; //set start img to 10
xSlider.css({backgroundImage : 'url(images/' + loopvar + '.jpg)'}); 
document.onmousemove = function(e){
        var mouseposimg = Math.floor(e.pageX / Math.floor($(window).width() / 20) + 1);
        if (mouseposimg > 20) { mouseposimg = 21; } //if outside browser
        if (mouseposimg < 0) { mouseposimg = 1; }

        if(loopvar != mouseposimg) { 
            xSlider.css({backgroundImage : 'url(images/' + mouseposimg + '.jpg)'}); 
            loopvar = mouseposimg; 
        }


};

});

CSS

#third{
background: no-repeat 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

}

HTML

<div id="third">
</div> 

忘了提我用这个预加载

(function(d){var h=[];d.loadImages=function(a,e){"string"==typeof a&&(a=[a]);for(var f=a.length,g=0,b=0;b<f;b++){var c=document.createElement("img");c.onload=function(){g++;g==f&&d.isFunction(e)&&e()};c.src=a[b];h.push(c)}}})(jQuery);

$.loadImages(['1.jpg', '2.jpg', etc etc etc])

4

2 回答 2

6

闪烁可能是由于图像加载。您可以只预加载所有图像来防止这种情况发生:

for (var x = 1; x <= 21; x++) {
    (new Image).src = 'images/' + x + '.jpg';
}
于 2013-02-04T22:53:02.630 回答
1

听起来您需要先预加载图像。获取imagesLoaded插件并尝试以下操作:

function preload(sources, callback) {
    if(sources.length) {
        var preloaderDiv = $('<div style="display: none;"></div>').prependTo(document.body);

        $.each(sources, function(i,source) {
            $("<img/>").attr("src", source).appendTo(preloaderDiv);

            if(i == (sources.length-1)) {
                $(preloaderDiv).imagesLoaded(function() {
                    $(this).remove();
                    if(callback) callback();
                });
            }
        });
    } else {
        if(callback) callback();
    }
}

$(document).ready( function() {
    var xSlider = $("#third"); //cache
    var loopvar = 10; //set start img to 10

    var filesToPreload = [];
    for(var x = 1; x <= 21; x++) filesToPreload.push('images/' + x + '.jpg');

    preload(filesToPreload, function() {
        xSlider.css({backgroundImage : 'url(images/' + loopvar + '.jpg)'}); 

        document.onmousemove = function(e){
            var mouseposimg = Math.floor(e.pageX / Math.floor($(window).width() / 20) + 1);
            if (mouseposimg > 20) { mouseposimg = 21; } //if outside browser
            if (mouseposimg < 0) { mouseposimg = 1; }

            if(loopvar != mouseposimg) { 
                xSlider.css({backgroundImage : 'url(images/' + mouseposimg + '.jpg)'}); 
                loopvar = mouseposimg; 
            }
        }
    });
});

另请参阅:使用 JavaScript/jQuery 预加载图像的最终最佳方法?

于 2013-02-04T23:01:44.290 回答