jQuery on window scroll animate background image position

前端 未结 6 2294
小鲜肉
小鲜肉 2020-12-12 18:26

I am trying to achieve a scrolling effect using jQuery. I have a background div set to 100% browser window size with overflow hidden. This has a large background image that

6条回答
  •  半阙折子戏
    2020-12-12 18:53

    If you don't want to be hassled with the extra background div, here's my code I wrapped up from several examples:

    $(window).scroll(function () {
        setBackgroundPosition();
    })
    $(window).resize(function() {
        setBackgroundPosition();
    });
    function setBackgroundPosition(){
        $("body").css('background-position', "-" + (1920 - $(window).width()) / 2 + "px " + -(Math.max(document.body.scrollTop, document.documentElement.scrollTop) / 4) + "px");
    }
    

    The Math.max is required for cross-browser issues. Also replace '1920' with the width of your background image

    body{
        background-image:url(images/background.jpg);
        background-position:center top;
        background-repeat:no-repeat;
        background-attachment:fixed;
    }
    

提交回复
热议问题