我最近问了一个问题,在处理了大约 5 个小时(不幸的是,很严重)之后,我能够平滑滚动到 anchor 。这是我放入的js。
$(document).ready(function(e) {
$(".scroll").click(function(event){
event.preventDefault();
//calculate destination place
var dest=0;
if($(this.hash).offset().top > $(document).height()-$(window).height()){
dest=$(document).height()-$(window).height();
}else{
dest=$(this.hash).offset().top;
}
//go to destination
$('html,body').animate({scrollTop:dest}, 1000,'swing');
});
});
我目前使用 ID 作为 anchor ,但如果您愿意,我也可以切换到 NAME。
这就是我想要的:这只适用于同一页面。我希望它可以跨多个页面工作。
这是我的示例:This page ,应该加载this page然后滚动到 anchor 。
但相反,它会跳跃。我应该在这段代码中添加什么?作为一名图形和 html/css 设计师,javascript 对我来说就像火箭科学。因此,如果您保持沉默,我将不胜感激。
最佳答案
坚持使用 JS,并传递一个 hash 属性:
<a href="http://something.com/some.php#start"> Go to page 2 ( Start ) </a>
<a href="http://something.com/some.php#goats"> Go to page 2 ( Goats ) </a>
并在第2页上使用简单的JS进行检查
<script>
$(document).one("ready",function(){
if( window.location.hash.length > 0 ){
$("body, html").animate({scrollTop:$(window.location.hash).position().top},1000);
}
});
</script>
该脚本将生成 ID 为“start”(或 ID 为“goats”)的对象 您可以在第 2 页上定义目标,并向您的部门添加 ID:
<div id="start"> Some content </div>
<div id="goats"> Goat content </div>
关于javascript - Jquery Smooth Scroll 仅在内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24774177/