[英]Jquery Autocomplete _renderItem does not work when Function is called a second time
[英]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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.