background image that moves when you scroll down the page

前端 未结 3 1510
野性不改
野性不改 2021-01-31 23:10

I keep seeing websites with a background image that subtly moves when you scroll down. This is a really nice effect but I\'m not sure how to do this? I\'m am experienced with

3条回答
  •  没有蜡笔的小新
    2021-01-31 23:45

    Like TylerH said, it's called Parallax. You can see an example here.

    Using JavaScript:

    var velocity = 0.5;
    
    function update(){ 
    var pos = $(window).scrollTop(); 
    $('.container').each(function() { 
        var $element = $(this);
        // subtract some from the height b/c of the padding
        var height = $element.height()-18;
        $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) +  'px'); 
       }); 
       };
    
     $(window).bind('scroll', update);
    

提交回复
热议问题