简体   繁体   English

相对于当前位置滚动

[英]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. 我正在尝试使用jquery单击元素时相对于其当前位置滚动div。 But it has to scroll after 3000 miliseconds, so tried to delay it. 但是它必须在3000毫秒后滚动,因此尝试延迟它。 Now it scroll 300 px relative to the top immidiatly after clicking. 现在,点击后,它会相对于顶部滚动300像素。 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. Brad M关于使用setTimeout的建议是获得所需内容的一种方法。 scrollTop() is not listed among the "effect" provided by jQuery and thus won't be affected by delay() because delay() only affects effects. scrollTop()未在jQuery提供的“效果”中列出,因此不会受到delay()影响,因为delay()仅影响效果。

However, it is possible to use animate() to make an effect out of scrolling, for instance the following should animate the scrolling: 但是,可以使用animate()来实现滚动效果,例如,以下内容应使滚动动画:

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

Since animate() is an "effect", it should be affected by delay() . 由于animate()是“效果”,因此应受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 . 但是,您遇到了另一个问题:当调用scrollTop(x)x绝对值 ,而不是相对 Calling scrollTop(+300) is exactly the same as calling scrollTop(300) . 调用scrollTop(+300)与调用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. 如果希望滚动是相对的,则需要首先获取先前的scrollTop值,然后将要滚动的相对距离添加到该值。 For instance, 例如,

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

This fiddle puts the above principles to work. 这个小提琴使上述原理起作用。

This is not how delay() works. 这不是delay()工作方式。

In your case, use 根据您的情况使用

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

Per the documentation for delay() 根据有关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. 例如,这不会延迟不使用效果队列的.show()或.hide()的无参数形式。

You could try something like this... 您可以尝试这样的事情...

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

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

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