根据窗口大小删除视差

时间:2019-05-15 21:45:34

标签: javascript jquery parallax

我的页面上有视差效果,并且想在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>

1 个答案:

答案 0 :(得分:1)

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


$.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

相关问题