【发布时间】:2015-03-09 03:30:49
【问题描述】:
我的 jQuery 有问题,我有一个包含多个锚点的网站,我使用平滑滚动转到锚点。问题是我在 URL 中有锚点。
这是我的代码:
/**
* Checks if anchor exists. If it exists, scroll to it
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");
// dynamically caluclates height
var fromTop;
var speed = 750; // Durée de l'animation (en ms)
var headerHeight = $('#header').height(),
navHeight = $('.nav-secondaire').height();
if( headerHeight + navHeight > 200){
fromTop = 300;
} else {
fromTop = 120;
}
// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
if(href.indexOf("#") == 0) {
var $target = $(href);
// Older browser without pushState might flicker here, as they momentarily
// jump to the wrong position (IE < 10)
if($target.length) {
$('html, body').animate({ scrollTop: $target.offset().top - fromTop }, speed);
if(history && "pushState" in history) {
history.pushState({}, document.title, window.location.pathname + href);
return false;
}
}
}
}
// When page loads, scroll to anchors
scroll_if_anchor(window.location.hash);
// Intercept all clicks on anchors
$("body").on("click", "a", scroll_if_anchor);
你有什么想法吗?
非常感谢!
【问题讨论】:
-
我不明白问题出在哪里。页面没有滚动到所需位置吗?
-
Do you have an idea不是正确的问题陈述 请解释您遇到的问题。
标签: javascript jquery