简体   繁体   中英

ScrollTop works in Chrome and Edge but not Firefox

So I have a JavaScript function that scrolls to the desired element when that part of the navigation bar is clicked. It works fine in Chrome and Edge, but not Firefox or IE.
The function:

$('html', 'body').animate({
  scrollTop:$('.'+nextView).offset().top}, 1500
);

nextView is a variable from another function where it determines which part of the nav was clicked. Basically, it contains the name of the div to be scrolled into view.

Anyone know why it doesn't work? Or an alternative method of auto scrolling that will work?

Try .position() instead of .offset() to see if that works. Might require some correction.

EDIT: it's probably related to your selector. Use html, body as 1 string:

$('html, body').animate({
  scrollTop:$('.'+nextView).offset().top}, 1500
);

I made a slight change to the code and now it seems to work. I find the position of the element to be scrolled to before the animate call, then put that variable into the scrollTop and it works now, even in IE!

scrollPos = $('.'+nextView).offset().top;
$('html, body').animate({
  scrollTop: scrollPos
}, 1500);

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