最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scroll to top of an element without using animate - Stack Overflow

programmeradmin1浏览0评论

HOw can I scroll to top of an element without using animate()? I googled, but all answers are with animate().

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

I just want to instantly go to the top of an element. In my case, the animate() is not necessary.

HOw can I scroll to top of an element without using animate()? I googled, but all answers are with animate().

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

I just want to instantly go to the top of an element. In my case, the animate() is not necessary.

Share Improve this question asked Jul 31, 2015 at 3:01 BekkiBekki 7292 gold badges12 silver badges20 bronze badges 1
  • 2 why don't you use just plain HTML (anchors)? – dpedoneze Commented Jul 31, 2015 at 3:10
Add a ment  | 

3 Answers 3

Reset to default 4

Use .scrollTop()

$("#button").click(function() {
  $('html, body').scrollTop( $("#elementtoScrollToID").offset().top);
});
.dummy {
  height: 1200px;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button">Test</button>
<div class="dummy"></div>
<div id="elementtoScrollToID">elementtoScrollToID</div>

You can do it just passing an anchor, pure HTML:

<a href="#top">go to top</a>

and you just add an <a name="top"></a> on the top of your website :)

You achieve the same affect without jQuery by using Window.scroll()

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论