我有一个网站,首页上有 anchor 链接,可以链接到页面的不同部分。我在二级页面上遇到了一个问题,每当他们点击引用主页上的部分的 anchor 链接时,它不会将它们带到该部分。我尝试使用完整的 URL http://www.website.com/index.php#1但这只需要到主页,但不会触发 anchor 链接的位置。有什么我想念的吗?
我正在使用以下 Jquery 来实现平滑滚动并在菜单位于特定部分时激活菜单滚动。
<script>
var timerid; //Used to fire scroll function once after scrolling is done.
$(document).ready(function(){
$("#menu-main-menu a").click(function(e){
e.preventDefault();
$("#menu-main-menu a").removeClass('active');
var id = $(this).attr("href").substring(1);
$("body").animate({
'scrollTop': $("section#" + id).offset().top -133
});
});
$("body").scrollTop(1); //forcing window scroll to execute on page load
$(window).scroll(function(){
clearTimeout(timerid);
timerid = setTimeout(checkactivelink, 50);
});
function checkactivelink()
{
$("section").each(function(){
if($("body").scrollTop() >= $(this).offset().top -133)
{
$("#menu-main-menu a").removeClass('active');
$("#menu-main-menu a[href=#" + $(this).attr("id") + "]").addClass('active');
}
});
}
});
</script>
最佳答案
尝试替换
$("body").scrollTop(1);
与:
if(location.hash) {
$("#menu-main-menu a[href='"+location.hash+"']").click();
}
因此当您打开链接中带有 anchor 的页面时,它会模拟点击相应的导航菜单。
关于jquery - anchor 链接到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25269751/