开发者

window.location.replace vs scrollTop

开发者 https://www.devze.com 2023-03-17 00:48 出处:网络
I am running on Chrome with the following snippets: <a name=\"example\">&nbsp;</a> The following code works correctly. It actually goes to #example as expected.

I am running on Chrome with the following snippets:

<a name="example">&nbsp;</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');});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号