scrollTop jquery, scrolling to div with id?

2019-02-01 05:43发布

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

5条回答
狗以群分
2楼-- · 2019-02-01 06:08

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

查看更多
萌系小妹纸
3楼-- · 2019-02-01 06:16

My solution was the following:

document.getElementById("agent_details").scrollIntoView();
查看更多
Juvenile、少年°
4楼-- · 2019-02-01 06:25

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

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

use

$('#mydivid').animate(...
查看更多
狗以群分
5楼-- · 2019-02-01 06:25

try this

    $('#div_id').animate({scrollTop:0}, '500', 'swing');
查看更多
forever°为你锁心
6楼-- · 2019-02-01 06:30

try this:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();
查看更多
登录 后发表回答