使用scrollTop的奇怪行为 [英] Strange behavor using scrollTop

查看:108
本文介绍了使用scrollTop的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用scrollTop JQuery函数有一种奇怪的行为。我有一个div包含一个复杂的文本,分成不同的部分,如下所示:

I've a strange behavor using scrollTop JQuery function. I've a div that contains a complex text divided in different sections like this:

<div id="wrapper" ... >
    <div id="section1">
        <h1>Section 1</h1>
        Lorem ipsum dolor sit amet, consectetuer... 
        ...
    </div>
    <div id="section2">
        <h1>Section 2</h1>
        Lorem ipsum dolor sit amet, consectetuer... 
        ...
    </div>
    <div id="section3">
        <h1>Section 3</h1>
        Lorem ipsum dolor sit amet, consectetuer... 
        ...
    </div>
    ...

第二个DIV包含一个简单的部分列表,当用户点击时他们每个我想要在右边部分包装滚动:

a second DIV contains a simple list of sections and when user click on each of them I want wrapper scroll at the right section:

<li>
   <a href="#" onclick="customScrollTo('section1')">section1</a>
</li>
<li>
   <a href="#" onclick="customScrollTo('section2')">section2</a>
...

这是JS函数的简单:

function customScrollTo (section) {

     $('#wrapper').animate({
         scrollTop: $("#wrapper div[id='" + section + "']").offset().top
     }, 200);
};

现在如果您尝试在此JSfiddle中测试它:
http://jsfiddle.net/Ws5F9/4/

now if you try to test it in this JSfiddle: http://jsfiddle.net/Ws5F9/4/

你可以看到两个奇怪的行为:

you can see two strange behavors:


  1. 如果你点击'section 1'而不是'section 2'而不是'section 3',第3节没有'工作!

  2. 如果你在同一部分链接上点击两次,第二次在页面顶部滚动


推荐答案

customScrollTo 方法存在两个问题。

首先,您使用 .offset()而不是 .position()。这将返回相对于文档的位置,而不是 #wrapper div。这里几乎没有引起注意,因为div无论如何都接近文档的顶部,但是当你将它向下移动到页面时你会遇到麻烦。

First, you are using .offset() instead of .position(). This is returning the position relative to the document rather than the #wrapper div. This is barely noticeable here because the div is close to the top of the document anyway, but you'd run into trouble as you moved it further down the page.

第二,当你调用position时,它将返回元素的位置,考虑到当前滚动位置,所以如果你已经滚动到文档的顶部已经按预期工作,但任何由于文档已被移动,进一步滚动会导致麻烦。你需要考虑当前的滚动位置,并将其添加到最终的滚动值,这样它就不会丢失。

Second, when you call position it is going to return the position of the element taking into account the current scroll position, so if you are scrolled to the top of the document already it will work as expected, but any further scrolling will cause trouble, since the document has been moved. You need to take into account the current scroll position as well by adding it in to the final scroll value so it doesn't get 'lost'.

这是一个例子解决了这两个问题:

Here is an example with both issues addressed:

function customScrollTo (section) {

     $('#wrapper').animate({
         scrollTop: $("#wrapper div[id='" + section + "']").position().top + $("#wrapper").scrollTop()
     }, 200);
 };

这篇关于使用scrollTop的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆