如何使用 jQuery 滚动到元素? [英] How can I scroll to an element using jQuery?

查看:35
本文介绍了如何使用 jQuery 滚动到元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望页面滚动到页面顶部的 div.我有页面其他部分的按钮,但是当我滚动到底部并单击该按钮时,这不起作用.它不会转到页面顶部.

这是 CodePen:https://codepen.io/Filizof/pen/xygWyp?editors=1010

$(document).ready(function() {$("#btn1").click(function() {$("body").scrollTo("#menudiv");});});

解决方案

JavaScript 答案

如果您想使用纯 JavaScript"平滑滚动到元素你可以这样做:

document.querySelector('#menudiv').scrollIntoView({行为:平稳"});

更多信息在这里:Element.scrollIntoView()

注意:请参阅我可以使用...支持 HTML5、CSS3 等表格. 获得最新的浏览器支持...

jQuery 答案

如果您想使用 jQuery 平滑滚动到一个元素,那么您可以执行以下操作:

$(document).ready(function() {$(".btns").click(function() {$(html").animate({scrollTop: $("#menudiv").offset().top},800//速度);});});

示例:https://jsbin.com/xaciloteqe/1/edit?html,js,输出


这可能对研究此主题的人有所帮助:

可取消"平滑滚动

I want the page to scroll to a div that's at the top of the page. I have buttons for other parts of the page, but this isn't working when I scroll to the bottom and click on the button. It doesn't go to the top of the page.

Here is the CodePen: https://codepen.io/Filizof/pen/xygWyp?editors=1010

$(document).ready(function() {
    $("#btn1").click(function() {
        $("body").scrollTo("#menudiv");
    });
});

解决方案

JavaScript answer

If you would like to scroll to an element smoothly with "pure JavaScript" you could do something like this:

document.querySelector('#menudiv').scrollIntoView({
    behavior: 'smooth'
});

More information is here: Element.scrollIntoView()

NOTE: Please see Can I use... Support tables for HTML5, CSS3, etc. for the latest browser support...

jQuery answer

If you would like to scroll to an element smoothly using jQuery then you could do something like:

$(document).ready(function() {
  $(".btns").click(function() {
    $("html").animate(
      {
        scrollTop: $("#menudiv").offset().top
      },
      800 //speed
    );
  });
});

Example: https://jsbin.com/xaciloteqe/1/edit?html,js,output


This might be helpful for people researching this topic:

"Cancelable" Smooth Scrolling

这篇关于如何使用 jQuery 滚动到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆