Consider the following JS code:
<script type="text/javascript">
$(function() {
// Check if landing on the page with a hash
if (window.location.hash.length) {
$('html,body').animate({scrollTop: 200}, 100);
return false;
}
// Same-page anchors
$('a[href*=#]').click(function() {
// ... find the target based on the div and animate the scrollTop property again
}
});
});
</script>
What it does is first check if landing on a page with an #anchor or if the user is clicking an same-page #anchor and simply animate to the target div with the corresponding id.
The problem is that these 2 work alternatively: if you land on a page with a hash symbol the page will animate to the div ID, but the subsequent same-page links won't be intercepted by the bound 'click' event (I've also tried binding it with live(), no difference)
If you land on the page with a clean URL, the links will work again. What am I doing wrong?
Why do you return false? That does not make any sense, because in a "ready" event handler, there is no default behavior that can be prevented or a DOM tree that will be bubbled up. Plus it prevents the following statements from being executed (specifically the binding of the event handlers to the links).
if (window.location.hash.length) {
$('html,body').animate({scrollTop: 200}, 100);
return false; // <-- remove this line!
}
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.