scrollTop jquery, scrolling to div with id?

2019-02-01 06:04发布

问题:

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

回答1:

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



回答2:

try this:

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


回答3:

My solution was the following:

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


回答4:

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:

try this

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