如何使用JQuery滚动到元素? [英] How to scroll to an element using JQuery?
问题描述
我希望页面滚动到页面顶部的div.我在页面的其他部分有按钮,但是当我滚动到底部并单击该按钮时,此按钮不起作用,它没有转到页面的顶部.这是CodePen: https://codepen.io/Filizof/pen/xygWyp?editors = 1010
I want the page to scroll to a div that's the at the top of the page. I have buttons for others part 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解答:
如果您想使用纯javascript"顺利滚动到某个元素,则可以执行以下操作:
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'
});
示例: https://codepen.io/anon/pen/OBzbdY
注意:有关最新的浏览器,请参见 https://caniuse.com/#feat=scrollintoview 支持.
NOTE: Please see https://caniuse.com/#feat=scrollintoview for latest browser support..
如果您想使用"jquery"平滑滚动到某个元素,则可以执行以下操作:
If you would like to scroll to an element smoothly using "jquery" then you could do something like:
$(document).ready(function() {
$("#btn1").click(function() {
$("body,html").animate(
{
scrollTop: $("#menudiv").offset().top
},
800 //speed
);
});
});
示例: https://codepen.io/anon/pen/MPrJjo
这篇关于如何使用JQuery滚动到元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!