这篇文章主要讲解了“css怎么实现平滑滚动效果”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“css怎么实现平滑滚动效果”吧!
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>锚点平滑跳转</title>
<style>
* {
margin: 0;
padding: 0;
}
html {
scroll-behavior: smooth;
}
nav {
width: 50%;
height: 50px;
text-align: center;
position: fixed;
left: 50%;
transform: translateX(-50%);
top: 0;
background: green;
}
nav a {
display: inline-block;
line-height: 50px;
color: #FFF;
text-decoration: none;
padding: 0 30px;
}
.box {
width: 100%;
text-align: center;
font-size: 30px;
color: #FFF;
}
#box1 {
background: #d00;
}
#box2 {
background: #42a4ff;
}
#box3 {
background: #008080;
}
#to-top {
position: fixed;
bottom: 20px;
right: 20px;
border-radius: 50%;
width: 80px;
height: 80px;
background: #ccc;
color: #666;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
</style>
</head>
<body>
<nav>
<a href="#box1">box1</a>
<a href="#box2">box2</a>
<a href="#box3">box3</a>
</nav>
<div id="box1" class=" box">box1</div>
<div id="box2" class=" box">box2</div>
<div id="box3" class=" box">box3</div>
<div id="to-top">回到顶部</div>
<script>
onload = function () {
const _Height = document.documentElement.clientHeight;
const Box = document.getElementsByClassName('box');
for (var i = 0; i < Box.length; i++) {
Box[i].style.height = _Height + 'px'
Box[i].style.lineHeight = _Height + 'px'
}
document.querySelector('#to-top').onclick = function (el) {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
}
</script>
</body>
</html>
html {
scroll-behavior: smooth;
}
这样,在回到顶部的时候,会有动画不会立即过去,或有渐变动画
锚点,切换屏幕的时候也会有动画
.querySelector('#to-top').onclick = function (el) {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
感谢各位的阅读,以上就是“css怎么实现平滑滚动效果”的内容了,经过本文的学习后,相信大家对css怎么实现平滑滚动效果这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.51cto.com/u_12836588/5742043