根据 window 大小移除视差

Remove parallax based on window size

我的页面上有视差效果,想在 768 或更小的屏幕上禁用该效果。我该如何着手完成这项任务?这是我用的javascript。

<script>
$(window).scroll(function(){

// Add parallax scrolling to all images in .paralax-image container
  $('.parallax-image').each(function(){
    // only put top value if the window scroll has gone beyond the top of the image
        if ($(this).offset().top < $(window).scrollTop()) {
        // Get number of pixels the image is above the top of the window
        var difference = $(window).scrollTop() - $(this).offset().top;
        // Top value of image is set to half the amount scrolled
        // (this gives the illusion of the image scrolling slower than the rest of the page)
        var half = (difference / 2) + 'px',
            transform = 'translate3d( 0, ' + half + ',0)';

        $(this).find('img').css('transform', transform);
    } else {
        // if image is below the top of the window set top to 0
        $(this).find('img').css('transform', 'translate3d(0,0,0)');
    }
  });
});
</script>

您可以将代码包装在一个函数中,然后 运行 在加载和调整大小时。


$.load_parallax = function(){
      if ($(window).width() > 768) {
          $(window).scroll(function(){
             $('.parallax-image').each(function(){
                 //your code here
             });
           });
    }
}
    $(window).on('resize', function() {
       $.load_parallax(); //calls it on resize
    });

      $.load_parallax();//calls it on load