【发布时间】:2016-03-03 14:40:24
【问题描述】:
我从另一个 Stack Overflow 问题中得到了这个代码位,但似乎有一个小问题。当我从一个部分移动到另一个部分时,哈希会正确更改,但是当我尝试向上滚动时,它会跳到最顶部,而不是平滑的手动滚动。任何帮助将不胜感激:)
HTML
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<header>
</header>
<body>
<div class="main">
<section id="one" class="section"></section>
<section id="two" class="section"></section>
<section id="three" class="section"></section>
<section id="four" class="section"></section>
<section id="five" class="section"></section>
<section id="six" class="section"></section>
</div>
</body>
</html>
这里是 JS:
$(document).scroll(function(){
$('section').each(function(){
if (
$(this).offset().top < window.pageYOffset
//begins before top
&& $(this).offset().top + $(this).height() > window.pageYOffset
//but ends in visible area
//+ 10 allows you to change hash before it hits the top border
) {
window.location.hash = $(this).attr('id');
}
});
});
【问题讨论】:
-
所以与其跳起来,不如让它像使用滚动条一样滚动?
-
是的,它奇怪地跳了起来,除非我再次向下滚动,否则我无法回到上一节
标签: javascript jquery html hash