粘性定位(sticky)
前几天做项目遇到一个需要滚动到特定位置固定的情况。当时采用的方法是监听滚动,获取滚动位置,动态复制top
的方式。
当时的写法:
mounted() {
window.addEventListener('scroll', this.getScroll, true);
this.offsetTop = document.getElementById('customTabs').offsetTop;
},
getScroll(){
const scrollTop = document.getElementById('home').scrollTop;
if (scrollTop < this.offsetTop) {
this.scrollTop = scrollTop;
}
},
然后今天看博客的时候无意看到sticky 粘性定位。可以更简单的实现。
eg:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.box {
position: relative;
margin: 0 auto;
border: 2px solid #1790FF;
padding-top: 40px;
width: 400px;
height: 1500px;
background: #f5f5f5;
}
.head{
position: sticky;
top: 0;
left: 0;
width: 100%;
line-height: 40px;
color: #fff;
background: #1790FF;
}
</style>
</head>
<body>
<div class="box">
<div class="head">固定导航</div>
内容
</div>
</body>
</html>
最后附上sticky的兼容性: