繁体   English   中英

使用 Jquery 和 CSS 平滑鼠标向上滚动

[英]Smooth mouse scroll upward using Jquery and CSS

我试图向上和向下平滑滚动,但后续图像有问题。

  $(window).scroll(function(event) {
    var scroll = $(window).scrollTop();

    if (scroll < 400) {
      $('#two').css('position', 'fixed');
      $('#three').css('position', 'fixed');
    }    

    if (scroll > 400 && scroll < 900) {
      $('#two').css('position', 'absolute');
      $('#three').css('position', 'fixed');
    }  


  });

https://jsfiddle.net/KingJef/6q47vmhn/32/

我发现了一个问题,有一个类似的动态,下面的问题就可以做同样的在你的问题中笔者的建议:

$(document).ready(function() {

  $(window).scrollTop(1);

  var img1 = $('#one');
  var posimg1 = img1.position().top;
  var img2 = $('#two');
  var posimg2 = img2.position().top;
  var img3 = $('#three');
  var posimg3 = img3.position().top;
    
  $(window).scroll(function(event) {

    var scroll = $(window).scrollTop();
    
    if (scroll <= posimg1) {
      img1.addClass('latched');
    } else {
      img1.removeClass('latched');
    }
    if (scroll <= posimg2) {
      img2.addClass('latched');
    } else {
      img2.removeClass('latched');
    }
    if (scroll <= posimg3) {
      img3.addClass('latched');
    }

  });
});

演示: https : //jsfiddle.net/pr0mming/ybar8onj/14/

显然,错误是使用 css 保留absolute图像,而不是将它们保留为fixed并且一旦超过滚动(可见度级别),该属性将被消除,否则图像应保持为fixed

但是有一个使用相同算法的更短的解决方案,当然,它只是添加这个神奇的 css并根据情况将其删除:

$(document).ready(function() {
  $(window).scroll(function(event) {
    var scroll = $(window).scrollTop();

    if (scroll < 500) {
      $('#two').css('position', 'fixed');
      $('#three').css('position', 'fixed');
    }

    if (scroll > 500 && scroll < 1600) {
      $('#two').removeAttr( 'style' );
      $('#three').css({ position: 'fixed', top: 0, width: 'auto' });
    }
    else {
      $('#two').css({ position: 'fixed', top: 0, width: 'auto' });
      $('#three').css({ position: 'fixed', top: 0, width: 'auto' });
    }

  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM