我刚开始使用 JS 并在苦苦挣扎。我从 Adam Khoury 那里得到了这段可爱的代码,它可以在页面向下滚动到目标元素时运行精美的动画。
位于ul
固定位置的导航栏中。
我的问题是:单击中的锚点时需要什么代码来使动画上下滚动nav
?
var scrollY = 0;
var distance = 10;
var speed = 24;
function autoScrollTo(el) {
var currentY = window.pageYOffset;
var targetY = document.getElementById(el).offsetTop;
var bodyHeight = document.body.offsetHeight;
var yPos = currentY + window.innerHeight;
var animator = setTimeout('autoScrollTo(\'' + el + '\')', 24);
if (yPos > bodyHeight) {
clearTimeout(animator);
} else {
if (currentY < targetY - distance) {
scrollY = currentY + distance;
window.scroll(0, scrollY);
} else {
clearTimeout(animator);
}
}
}
function resetScroller(el) {
var currentY = window.pageYOffset;
var targetY = document.getElementById(el).offsetTop;
var animator = setTimeout('resetScroller(\'' + el + '\')', speed);
if (currentY > targetY) {
scrollY = currentY - distance;
window.scroll(0, scrollY);
} else {
clearTimeout(animator);
}
}
<ul class="main-nav">
<li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
About</a>
</li>
<li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
Testimonials</a>
</li>
<li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
Contact</a>
</li>
</ul>
<hr style="margin: 25em 0;" />
<div id="about" class="navButton">
<p>About lorem ipsom....</p>
</div>
<div id="testimonials" class="navButton">
<p>Testimonial lorem ipsom....</p>
</div>
<div id="contact" class="navButton">
<p>Contact lorem ipsum</p>
</div>