iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 14
0
Modern Web

從Stack Overflow學前端系列 第 14

從StackOverflow上學CODING(14)用JS達成捲動到頁面頂端

Scroll to the top of the page using JavaScript/jQuery?

I've a on the page, when this button is pressed a hidden is shown using jQuery.
我有一個在頁面上,點擊後一個隱藏的div會透過jQuery顯示
How do I scroll to the top of the page using a JavaScript/jQuery command in that function? It is desirable even if the scroll bar instantly jumps to the top. I'm not looking for a smooth scrolling.
我該如何用JavaScript/jQuery達成點擊後立刻跳到頁面頂端?


1.純JS
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.
如果你不在乎動畫效果,那你就不用用特殊的插件,直接用window.scrollTo方法就可以了,

window.scrollTo(x-coord, y-coord);

Parameters
參數x-coord掌控平行的點、y-coord則是垂直的點
x-coord is the pixel along the horizontal axis.
y-coord is the pixel along the vertical axis.

2.jQuery
If you do want smooth scrolling, try something like this:
如果你想達到平滑的捲動可以試試看這樣:

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

That will take any tag whose href="#top" and make it smooth scroll to the top.


上一篇
從StackOverflow上學CODING(13)用js獲取screen, web page 與 browser window大小
下一篇
從StackOverflow上學CODING(15)如何用JS移動html元素
系列文
從Stack Overflow學前端30

尚未有邦友留言

立即登入留言