问题
When I load a page with a hash tag in the URL, the page loads and then jumps to the anchor tag. Is there any way to prevent this "jump", either by loading the page directly to the anchor tag or at least making the scrolling smooth?
I see this problem in Chrome and Firefox, but not IE.
回答1:
If you're still experiencing the jumping issue, you could something with jQuery:
//Use a RegEx pattern to search for an id, if present
var pattern = new RegExp('\#(.*)');
var id = pattern.exec(window.location)[0].replace('#','');
//Prevent the browser's default behavior of jumping to the id
document.location = '#';
//When the page finishes loading, smoothly scroll to the specified content
$(document).ready(function() {
if(id != "") {
$('html,body').animate({
scrollTop: $('#' + id).offset().top,
}, 650);
}
});
Note that this will only work once per page load.
来源:https://stackoverflow.com/questions/21709638/load-page-directly-to-anchor-tag