我们在为客户开发网站的时候经常会使用到吸顶的效果,那是怎么实现的呢下面就说说如何通过js实现吸顶效果:
js实现吸顶效果的思路:
1. 页面div初始居普通文档流中
2. 给window添加scroll事件,获取div的offset的top值,滚动时scrollTop值和top比较,当到达top时给div添加一个fixed的class使其固定在窗体中
3. 滚动条向上滚动时当到达div初始top时则删除fixed的class,此时div又回到普通文档流中
4. fixed样式非IE6浏览器使用position:fixed,IE6使用position:absolute和IE expression
代码如下:
* {
margin: 0;
padding: 0;
}
#div1 {
width: 100%;
height: 50px;
background: skyblue;
}
window.onload = function() {
var oDiv = document.getElementById('div1');
var divT = oDiv.offsetTop;
//console.log(divT);
window.onscroll = function() {
// 获取当前页面的滚动条纵坐标位置 (依次为火狐谷歌、safari、IE678)
var scrollT = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
//当滚动条处于吸顶元素时
if (scrollT >= divT) {
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
// 兼容IE6代码
oDiv.style.position = 'absolute';
oDiv.style.top = scrollT + 'px';
oDiv.style.left = 0 + 'px';
} else {
// 正常浏览器代码
oDiv.style.position = 'fixed';
oDiv.style.top = 0;
oDiv.style.left = 0;
}
} else
oDiv.style.position = '';
}
}
以上
以上
以上
以上
以上
以上
以上
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示
吸顶效果展示