如何在不使用animate()的情况下滚动到元素顶部?我用谷歌搜索了一下,但所有答案都是使用animate()。
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
我只想立即跳转到一个元素的顶部。在我的情况下,animate()不是必需的。
如何在不使用animate()的情况下滚动到元素顶部?我用谷歌搜索了一下,但所有答案都是使用animate()。
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
我只想立即跳转到一个元素的顶部。在我的情况下,animate()不是必需的。
$("#button").click(function() {
$('html, body').scrollTop( $("#elementtoScrollToID").offset().top);
});
.dummy {
height: 1200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button">Test</button>
<div class="dummy"></div>
<div id="elementtoScrollToID">elementtoScrollToID</div>
<a href="#top">go to top</a>
<a name="top"></a>
即可 :)您可以使用Window.scroll()
来实现相同的效果,而无需使用jQuery。
document.getElementById("button").onclick = function() {
window.scroll(0,document.getElementById("elementtoScrollToID").offsetTop);
};
<button id="button">Button</button>
<div id="elementtoScrollToID" style="margin: 800px 0;">
Scroll to here...
</div>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>