📜  使用 JavaScript/jQuery 滚动到页面顶部

📅  最后修改于: 2021-11-24 04:54:54             🧑  作者: Mango

可以使用两种方法将可滚动页面滚动到顶部:

方法一:使用window.scrollTo()
可以使用窗口接口的scrollTo()方法滚动到页面上的指定位置。它接受 2 个参数,即要滚动到的页面的 x 和 y 坐标。将这两个参数都传递为 0 会将页面滚动到最顶部和最左侧的点。

句法:

window.scrollTo(x-coordinate, y-coordinate)

例子:



  

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

  

    

      GeeksforGeeks   

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

Click on the button below to        scroll to the top of the page.

         

GeeksforGeeks is a       computer science portal. This is a        large scrollable area.

                 

输出:

  • 点击按钮前:
    滚动前 js
  • 点击按钮后:
    js 后滚动

方法二:在jQuery中使用scrollTo()

在 jQuery 中, scrollTo()方法用于设置返回所选元素的垂直滚动条位置。通过在 window 属性上应用此方法,此行为可用于滚动到页面顶部。将 position 参数设置为 0 会将页面滚动到顶部。

句法:

$(window).scrollTop(position);

例子:



  

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

  

    

      GeeksforGeeks   

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

      Click on the button below to        scroll to the top of the page.   

    

      GeeksforGeeks is a computer       science portal.        This is a large scrollable area.   

                 

输出:

  • 点击按钮前:
    滚动前 jq
  • 点击按钮后:
    jq 后滚动

JavaScript 以网页开发而闻名,但它也用于各种非浏览器环境。您可以按照此 JavaScript 教程和 JavaScript 示例从头开始学习 JavaScript。

jQuery 是一个开源 JavaScript 库,它简化了 HTML/CSS 文档之间的交互,它以其“少写,多做”的理念而广为人知。
您可以按照此 jQuery 教程和 jQuery 示例从头开始学习 jQuery。