Javascript scrollTop jquery,滚动到带有 id 的 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4565381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:59:48  来源:igfitidea点击:

scrollTop jquery, scrolling to div with id?

javascriptjquerycssscrollposition

提问by Jake

So this is the current code I have

所以这是我目前的代码

$(document).ready(function() {
    $('.abouta').click(function(){
        $('html, body').animate({scrollTop:308}, 'slow');
        return false;
    });
    $('.portfolioa').click(function(){
        $('html, body').animate({scrollTop:708}, 'slow');
        return false;
    });
    $('.contacta').click(function(){
        $('html, body').animate({scrollTop:1108}, 'slow');
        return false;
    });
});

When you click a link e.g. 'abouta' it scrolls to that specific section of the page. I'd rather do a scrollTo and then the id of a div so that I don't have to keep changing the scrollTo position if I change padding etc. Is there any way? Thanks

当您单击链接(例如“abouta”)时,它会滚动到页面的特定部分。我宁愿做一个scrollTo,然后是一个div的id,这样如果我改变填充等,我就不必不断改变scrollTo的位置。有什么办法吗?谢谢

回答by jondavidjohn

instead of

代替

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

这将返回您选择的任何元素的绝对顶部位置 #div_id

回答by Alexis Cabrera Mondeja

My solution was the following:

我的解决方案如下:

document.getElementById("agent_details").scrollIntoView();

回答by PauLo Guajardo Torrealba

try this:

尝试这个:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();

回答by pirate

try this

尝试这个

    $('#div_id').animate({scrollTop:0}, '500', 'swing');

回答by Fawas

if you want to scroll just only some div, can use the div id instead of 'html, body'

如果你只想滚动一些 div,可以使用 div id 而不是 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...