我正在尝试删除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'等等])
答案 0 :(得分:6)
闪烁可能是由于图像加载造成的。您可以预加载所有图像以防止这种情况:
for (var x = 1; x <= 21; x++) {
(new Image).src = 'images/' + x + '.jpg';
}
答案 1 :(得分: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;
}
}
});
});
另请参阅:The definitive best way to preload images using JavaScript/jQuery?