简体   繁体   中英

Smooth mouse scroll upward using Jquery and CSS

I am try to make a smooth scroll upward and downward but having issue with the follow up image. t

  $(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/

I have found a question with a similar dynamics, following the proposal of the author of the question it is possible to do the same in your question:

$(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');
    }

  });
});

Demo: https://jsfiddle.net/pr0mming/ybar8onj/14/

Apparently the error is to preserve the absolute images with css, instead of this they are left in fixed and the property would be eliminated once the scroll is exceeded (visibility level) but otherwise the images should be kept in fixed .

But there is a shorter solution with the same algorithm, of course, it is simply to add this magic css and remove it as the case may be:

$(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' });
    }

  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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