这篇文章主要介绍了js如何实现移动端吸顶效果,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体内容如下
先罗列一下吸顶需要使用到的属性
** scrollTop 获取当前滚动的距离(也就是盒子距离顶部的距离)
offsetTop 盒子距离顶部的高度
offsetHeight 盒子自身的高度
scrollY 滚动的距离
**
想要写出一个吸顶 一定要先明白这几个属性哦(当然了,他也很简单,相信您看完会有一定的收获)
根据图片中的思路来写:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
box-sizing:border-box;
}
.wrap{
overflow-y:scroll;
}
.header{
width: 100%;
height: 40px;
background: lightgreen;
color:#fff;
text-align: center;
line-height: 40px;
}
.main{
height: 1000px;
background: lightyellow;
}
.fixed{
position: fixed;
top:0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="header">我是即将吸顶的哦</div>
<div class="main"></div>
</div>
<script>
const head = document.querySelector('.header');
document.addEventListener('scroll',()=>{
//console.log(document.documentElement.offsetTop) // 0 html距离顶部的距离
//console.log(document.querySelector('.header').offsetHeight) // 40 红盒子的高度
//console.log(window.scrollY) // 滚动的距离
if(window.scrollY > head.offsetHeight){
head.classList.add('fixed')
}
})
</script>
</body>
</html>
感谢你能够认真阅读完这篇文章,希望小编分享的“js如何实现移动端吸顶效果”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。