简体   繁体   中英

Scroll relative to current position Jquery

I'm trying to scroll a div relative to its current position when clicking on an element using jquery. But it has to scroll after 3000 miliseconds, so tried to delay it. Now it scroll 300 px relative to the top immidiatly after clicking. if i click again nothing happends.

this is the code so far:

$('#scroll').click(function(){              
            $('.vluchtelinginfo').delay(3000).scrollTop(+300);
        });

Thanks for helping.

Brad M's recommendation about using setTimeout is one way to get what you want. scrollTop() is not listed among the "effect" provided by jQuery and thus won't be affected by delay() because delay() only affects effects.

However, it is possible to use animate() to make an effect out of scrolling, for instance the following should animate the scrolling:

$scrollable.animate({scrollTop: x});

Since animate() is an "effect", it should be affected by delay() . So you could do:

$scrollable.delay(3000).animate({scrollTop: x});

However, there is another problem you ran into: when scrollTop(x) is called x is an absolute value , not a relative one . Calling scrollTop(+300) is exactly the same as calling scrollTop(300) . The + symbol has no special meaning in that context. If you want your scrolling to be relative, then you need to first get the previous scrollTop value and add to it the relative distance you want to scroll. For instance,

$scrollable.delay(3000).animate({scrollTop: $scrollable.scrollTop() + 300});

This fiddle puts the above principles to work.

This is not how delay() works.

In your case, use

setTimeout(function() {
    $('.vluchtelinginfo').scrollTop(+300);
});

Per the documentation for delay()

Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

You could try something like this...

$("#scroll").click(function () {
    setTimeout(function () {
        $(".vluchtelinginfo").css("top", $(".vluchtelinginfo").offset().top + 300);
    }, 3000);
});

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