簡體   English   中英

jQuery animate 函數在第二次調用時重置滾動

[英]jQuery animate function is resetting scroll when called second time

我有一個要求,我必須滾動到DIV具有特定類的元素。 這應該發生在用戶點擊時。
為此,我選擇使用 jQuery 的animate()函數。 這工作正常。

第一次工作正常,但是當用戶再次單擊按鈕時,它會重置滾動位置。 並且第三次再次運行良好......

我知道這是因為我需要滾動的元素的offest量在滾動后發生了變化。

這是我的示例代碼:HTML:

<div class="scroll-div">
        <ul>
            <li>1. The Shawshank Redemption (1994)  9.2</li>
            <li>2. The Godfather (1972)     9.2</li>
            <li>3. The Godfather: Part II (1974)    9.0</li>
            <li>4. The Dark Knight (2008)   8.9</li>
            <li>5. 12 Angry Men (1957)  8.9</li>
            <li>6. Schindler's List (1993)  8.9</li>
            <li>7. Pulp Fiction (1994)  8.9</li>
            <li>8. The Lord of the Rings: The Return of the King (2003)     8.9</li>
            <li>9. The Good, the Bad and the Ugly (1966)    8.8</li>
            <li>10. Fight Club (1999)   8.8</li>
            <li>11. The Lord of the Rings: The Fellowship of the Ring (2001)    8.8</li>
            <li>12. Star Wars: Episode V - The Empire Strikes Back (1980)   8.7</li>
            <li>13. Forrest Gump (1994)     8.7</li>
            <li>14. Inception (2010)    8.7</li>
            <li>15. The Lord of the Rings: The Two Towers (2002)    8.7</li>
            <li>16. One Flew Over the Cuckoo's Nest (1975)  8.7</li>
            <li>17. Goodfellas (1990)   8.7</li>
            <li>18. The Matrix (1999)   8.7</li>
            <li>19. Seven Samurai (1954)    8.6</li>
            <li>20. Star Wars: Episode IV - A New Hope (1977)   8.6</li>
            <li>21. City of God (2002)  8.6</li>
            <li class="seven" style="color:red;">22. Se7en (1995)   8.6</li>
            <li>23. La La Land (2016)   8.6</li>
            <li>24. The Silence of the Lambs (1991)     8.6</li>
            <li>25. It's a Wonderful Life (1946)    8.6</li>
            <li>26. The Usual Suspects (1995)   8.6</li>
            <li>27. Life Is Beautiful (1997)    8.6</li>
            <li>28. Léon: The Professional (1994)   8.5</li>
            <li>29. Spirited Away (2001)    8.5</li>
            <li>30. Saving Private Ryan (1998)  8.5</li>
        </ul>
    </div>

    <input type="button" value="Scroll to Seven" onclick="scrollToSeven()" />

CSS:

.scroll-div{
  height: 100px;
  overflow-y: scroll;
  width: 300px;
  border: 1px solid #dfdfdf;
}

Java腳本:

function scrollToSeven(){
  $(".scroll-div").animate({
    scrollTop: $('.seven').offset().top - $('.scroll-div').offset().top
  }, 5);
}

這段代碼部署在JSFiddle 在這里你可以看到演示。

當您第一次單擊“ Scroll to Seven按鈕時,它會完美地滾動到元素。 如果您再次單擊它會重置回來。
如何使其適用於多次點擊? 如果有人遇到同樣的問題,請幫助。

這是更新的版本:

function scrollToSeven(){
    $(".scroll-div").animate({
        scrollTop:  $(".scroll-div").scrollTop() + $('.seven').offset().top
    }, 5);
}

https://jsfiddle.net/psjzgx2g/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM