gpt4 book ai didi

JavaScript 动画平滑滚动

转载 作者:行者123 更新时间:2023-11-28 01:54:53 25 4
gpt4 key购买 nike

默认情况下,当您有这样的片段链接时:

<a href="/some-url#some-fragment">some text</a>

浏览器立即向下滚动到该片段。我该如何编程才能使用标准 JS 顺利地向下移动到该片段?

这是一个例子:

Example (要查看工作示例,只需单击 3 个圆圈内的 3 个箭头即可观看平滑的动画滚动)

最佳答案

好吧,我想我找到了答案,将其发布在这里以帮助其他有类似疑问的人:

<html>
<head>
<script type="text/javascript">
var singleton = {};
var timeout = singleton;

window.onscroll = windowScroll;

function windowScroll ()
{
var toTop = document.getElementById('toTop');
toTop.style.display = ((window.scrollY > 0) ? "block" : "none");
}

function scrollStep ()
{
var y1 = window.scrollY - 1000;
window.scrollTo(0, y1);

if (y1 > 0)
{
timeout = window.setTimeout(scrollStep, 100);
}
else if (timeout != singleton)
{
window.clearTimeout(timeout);
}
}
</script>

<style type="text/css">
#toTop {
display: block;
position: fixed;
bottom: 20px;
right: 20px;
font-size: 48px;
}

#toTop {
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
transition: all 0.5s ease 0s;
opacity: 0.5;
display: none;
cursor: pointer;
}

#toTop:hover {
opacity: 1;
}
</style>
</head>

<body>
<p id="top">your text here</p>
<a href="#top" onclick="scrollStep(); return false" id="toTop"
><img src="images/go-to-top.png" alt="Go to top" title="Go to top"></a>
</body>
</html>

关于JavaScript 动画平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19268039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com