簡體   English   中英

使用jQuery有效創建簡單的視差效果

[英]Efficiently creating a simple parallax effect with jQuery

因此,對於我的一個新項目,我決定為滾動中的某些背景圖像編寫一個超級簡單的視差腳本。 這是我想出的:

$(document).ready(function(){
  parallaxScroll();
  $(window).bind('scroll', function() {
    parallaxScroll();
  });
});

function parallaxScroll() {
  $(".parallax").each(function() {
    if($(this).hasClass('reverse')) {
       $(this).css("background-position","center " + (($(this).offset().top - $(window).scrollTop())/2) + "px");
    } else {
       $(this).css("background-position","center " + (($(this).offset().top - $(window).scrollTop())/-2) + "px");               
    }
  });
}

我的問題是, 這足夠有效嗎? 如果沒有,是否有更好的解決方案? 我不確定是否可以使用.each()來提高性能,但是似乎可以正常使用。 我在文檔加載時運行該函數的原因是,因此,當您第一次滾動頁面時,背景圖像不會跳轉。

與其使用css立即設置值, animate考慮使用animate 它使用timers / requestAnimationFrame延遲設置值,確保您的動畫不會阻塞UI,是異步的(與其他代碼偽並行運行),並確保動畫流暢。

這是一個普通的JS解決方案,但是您可以非常輕松地將其移植到jQuery:

var lastScrollY = 0;
var backgroundImageY = 0;
var requestAnimationFrame = window.requestAnimationFrame ||
                            window.msRequestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame;

window.addEventListener('load', processScrollEvent);

function processScrollEvent() {
    var innerHeight = window.innerHeight;
    var scrollHeight = document.body.scrollHeight;
    var backgroundImage = document.querySelector('#background img');

    lastScrollY = document.body.scrollTop;

    var currBackgroundImageY = Math.round(((backgroundImage.scrollHeight - innerHeight) / 100) * ((lastScrollY / (innerHeight - scrollHeight)) * 100));

    if(currBackgroundImageY != backgroundImageY) {
        backgroundImageY = currBackgroundImageY;
        requestAnimationFrame(processScrollAnimationFrame);
    }
}

function processScrollAnimationFrame() {
    var backgroundImage = document.querySelector('#background img');
    var transforms = ['transform', 'oTransform', 'msTransform', 'mozTransform', 'webkitTransform'];

    for(var i = 0; i < transforms.length; i++) {
        backgroundImage.style[transforms[i]] = 'translate3d(0, ' + backgroundImageY + 'px, 0)';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM