简体   繁体   中英

Animate {“Top”} how to stop scrolling div on top position being 0 px - Jquery

Trying to create a scrolling div. Wanted to stop (thescrollingdiv) div once it has reached a particular top position and scrolled all the way to the bottom and not overshoot the parent div into infinity scrolling zone. thescrollingdiv does not have any height specified but its parent div does.Thanks.

$('#div a).click(function(e){ e.preventDefault(); $('#thescrollingdiv').stop(true,true).animate({ "top": '-=100px'}, 500)

ScrollTop tells you where you are at. Check the existing top against scrolltop and work the math to set your limits.

var scrollTop = $('#thescrollingdiv').scrollTop();
var newTop = parseFloat($('#thescrollingdiv').css('top')) - 100;

if (scrollTop < 0) {
  newTop = 0;
}

$('#thescrollingdiv').stop(true,true).animate({ "top": newTop}, 500)

UPDATE

Something like this.

var topLimit = 0;
var bottomLimit = 800;

var containerTop = parseFloat($('container').css('top'));
var containerBottom = parseFloat($('container').css('height')) + containerTop;

var destination = containerTop - 100;

// compensate for going too far up
destination = (destination < 0) ? 0 : destination;

// compensate for going too far up
destination = (containerBottom > bottomLimit) ? bottomLimit : destination;

// now that you know you are within your custom limits, animate it.
animate(destination);

This is almost pseudo code as I don't know what your code looks like, but it gives you an idea. You have to actually DO THE WORK in setting the limits for your 'newTop', before you call animate in the first place.

You can figure it out. Don't be a lazy programmer, though.

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