简体   繁体   中英

scrollTop not working in chrome

This snippet of code works in firefox but not in chrome it doesn't scroll - the click event fires but won't even go to its position on the anchor tag.

$(function() {
$(".menu li a").click(function(e) {
    var value = $(this).attr('href');
    var id = value.substr(1, $(this).attr('href').length);              
    var px = navigator.userAgent.toLowerCase().indexOf('firefox') > -1 ? 16 : 1;
    var target = $("a[name=" + id + "]").offset().top + px;

    console.log( $("a[name=" + id + "]"));

    $('html, body').stop().animate({
        scrollTop: target + 'px'
    }, 'slow');

    e.preventDefault();

});

})

scrollTop should be set with an integer , try not adding + 'px' .

For example, this will work:

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

If it doesn't for you then something else on the page is blocking scrolling, or your body/html doesn't have a scroll height bigger than the browser window.

You can further test with vanilla JavaScript by typing document.body.scrollTop = 200; in the console. If that doesn't scroll your page then something else is definitely wrong. Perhaps a Chrome Extension?

(Also firefox UA sniffing looks like trouble, but no one asked me :))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM