Going to the page I have linked at the end of my question with send you to the main stackoverflow page, but the browser wont display the top of the page, it will look for the #h-recent-badges
element and start your viewing of the page at that elements position.
Is it possible to make it so if someone comes to my site with a link to one of the comments at the bottom of the article, tha开发者_如何学Ct it will start the person off at the top of the page, then scroll it down to the #ID, instead of just appearing at the #ID?
I can make the page scroll to an #ID when an anchor link is clicked on the page, but i'm talking about when someone comes from google with a link to an element #ID.
https://stackoverflow.com/#h-recent-badges
Check out the jquery Query String plugin: http://plugins.jquery.com/project/query-object
The latest version has hash parameter parsing.
What you want to do is to grab the hash parameter once the page loads, then do something like $.scrollTo($("#" + hashValue)).
Check out http://flesler.blogspot.com/2007/10/jqueryscrollto.html for a scrollTo tutorial.
I might be wrong here but I believe this browser behavior is dependant on the speed which the website is loaded at...
for example, if I have a slower connection, it will take time to load it to the point where comments are available - and only THEN it can move to them (not before they actually apper on the page)
you can still try and use jQuery's scrollTo plugin to try and scroll the page manually (probably using preventDefault?) when page loads
$(document).ready(function() {
if(document.URL.indexOf('#') > 0){
var link = document.URL.split('#');
scrollId('#'+link[1])
}
});
$(window).on('hashchange', function(e){
if(document.URL.indexOf('#') > 0){
var link = document.URL.split('#');
scrollId('#'+link[1])
}
});
function scrollId(id)
{
setTimeout(function(){
$('html, body').animate({scrollTop: $(id).offset().top - 0 }, 'slow');
},500);
}
精彩评论