如何使用 jquery 或 javascript 滚动到特定的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19874912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to scroll to the particular div using jquery or javascript
提问by Jonathan
I want to scroll to the particular div using jquery
我想使用 jquery 滚动到特定的 div
I have written the code like:
我写的代码如下:
$("#button").on('click',function(){
var p = $("#dynamictabstrp");
var offset = p.offset();
window.scrollBy(offset.left, offset.top);
});
But it is not moving to the div position. How can i do that in jquery or javascript
但它并没有移动到 div 位置。我如何在 jquery 或 javascript 中做到这一点
回答by Anil kumar
Try this
尝试这个
$("#button").on('click',function() {
$('html, body').animate({
'scrollTop' : $("#dynamictabstrp").position().top
});
});
回答by Tushar Gupta - curioustushar
Try
尝试
$(window).scrollTop($('#dynamictabstrp').offset().top);
或者
$('#dynamictabstrp')[0].scrollIntoView(true);
or
或者
document.getElementById('dynamictabstrp').scrollIntoView(true);
回答by Subhajit
Here is the code :-
这是代码:-
$(document).ready(function (){
$("#button").on('click',function(){
$('html, body').animate({
scrollTop: $("#dynamictabstrp").offset().top
}, 1000);
});
});
or
或者
$(document).ready(function (){
$("#button").click(function(){
$('html, body').animate({
scrollTop: $("#dynamictabstrp").offset().top
}, 1000);
});
});
回答by JoyGuru
Try this simple script. Change #targetDiv
with your particular div ID or Class.
试试这个简单的脚本。更改#targetDiv
为您的特定 div ID 或类。
$('html,body').animate({
scrollTop: $('#targetDiv').offset().top
}, 1000);
The source code and live demo can be found from here - Smooth scroll to div using jQuery
可以从这里找到源代码和现场演示 -使用 jQuery 平滑滚动到 div
回答by sabin
You can set offset as per requirement
您可以根据需要设置偏移量
jQuery(document).ready(function(){
function secOffset(){
jQuery('html, body').animate({
scrollTop: jQuery(window.location.hash).offset().top - 60
}, 0);
}
});