页面吸顶的效果, 实现有两种, 最快的一种是用position: sticky方法, 不过该方法尚存在兼容性问题, 使用的时候需加入兼容方法。
使用方法跟position: fixed类似。 只要设定好吸顶时候的位置就行了。
<div class="title title_sticky"> Title </div>
<style>
.title {
height: 30px;
width: 100%;
line-height: 30px;
text-align: center;
background-color: #009975;
color: #ffffff;
}
.title_sticky {
position:-webkit-sticky;
position: sticky;
top: 0;
left: 0
}
</style>
第二种是用js来控制
思路很简单, 当滚动条滚动距离大于导航条距顶部的距离时,为导航条采用窗口固定
<div class="title" id="title"> title </div>
<style>
.title {
height: 30px;
width: 100%;
line-height: 30px;
text-align: center;
background-color: #009975;
color: #ffffff;
}
.title_fixed{
position: fixed;
top:0;
left: 0;
}
</style>
<script>
var obj = document.getElementById("title")
var ot = obj.offsetTop // title在页面中距离页面头部的高度
document.onscroll = function () {
var st = document.body.scrollTop || document.documentElement.scrollTop;
// 往下滚定时候, 滚动条距离顶部不断变大的高度(滚动距离)
if (st >= ot) {
obj.className = 'title title_fixed'
} else {
obj.className = 'title'
}
}
</script>
使用vuejs的话, 可以参考一下这篇文章https://www.cnblogs.com/_error/p/9648185.html, 实现方法也是js