最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scroll relative to current position Jquery - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jun 18, 2013 at 19:08 luukgruijsluukgruijs 1293 silver badges12 bronze badges 1
  • this is a misnomer - the actual question is about timing, not about scrolling or positioning – Berry Tsakala Commented Jan 15, 2020 at 8:13
Add a ment  | 

3 Answers 3

Reset to default 4

Brad M's remendation 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);
});
发布评论

评论列表(0)

  1. 暂无评论