问题
I tried to get the "background image change on scroll" working on my page. but while scrolling the changes are flickering. I couldn't find a solution in other threads.
This is what I have:
jquery:
$(function(){
$(document).scroll(function () {
if ($(this).scrollTop() > 1) {
$('body').css({
backgroundImage: 'url("img/picture1.jpg")'
});
}
if ($(this).scrollTop() > 800) {
$('body').css({
backgroundImage: 'url("img/picture2.jpg")'
});
}
CSS:
body {
background: url('../img/picture1.jpg');
background-repeat:no-repeat;
background-attachment:fixed;
background-size:cover;
}
回答1:
The flickering is probably due to the second image loading. You can preload the second image using javascript's native Image
object:
var newImg = new Image();
newImg.src = 'img/picture2.jpg';
See this jsfiddle.
来源:https://stackoverflow.com/questions/20448478/background-change-on-scroll-is-flickering