Background Change on Scroll is flickering

こ雲淡風輕ζ 提交于 2019-12-13 05:24:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!