window.location.replace vs scrollTop
I am running on Chrome with the following snippets:
<a name="example"> </a>
The following code works correctly. It actually goes to #example as expected.
window.location.replace('#example');
But the following does not work. It always go to the top of the page -- not to the #example
.
var target = $('a[name="example"]');
var offset = target.offset();
var top = offset.top;
console.log(top);
$('html, body').animate({scrollTop:top}, 'slow');
The top
returns value 500+ something.
What am I missing?
Thanks in advance for your help.
UPDATE:
After removing the following CSS
positi开发者_StackOverflow社区on: fixed;
The above jQuery code works!. But I need this page to be "position: fixed;". How do I make the above jQuery code works with "position: fixed;"?
Have you made sure that your document is tall enough in order to scroll up to that position. This jsFiddle using your own code and some HTML I made up to match it seems to work fine in Chrome.
if it works, you can add the fixed positioning after the animation is done:
var el = $('html, body');
el.animate({scrollTop:top}, 'slow',function(){el.css('position','fixed');});
精彩评论