html网页中吸顶栏效果,5行js代码搞定导航吸顶效果

一、HTML布局

首先写HTML布局

二、CSS样式

给点简单的样式

*{

margin: 0;

padding: 0;

}

body{

height: 2000px;

background-image: linear-gradient(-180deg, #15f09d 0%, #25A0FF 50%, #fca72b 100%);

}

#wrap{

background-color: rgba(0,0,0,0.2);

width: 100%;

height: 100px;

margin-top: 100px;

}

#wrap[data-fixed="fixed"]{

position: fixed;

top:0;

left: 0;

margin: 0;

}

三、JS代码

1、面向过程

直接编写5行代码搞定

var obj = document.getElementById("wrap");

var ot = obj.offsetTop;

document.onscroll = function () {

var st = document.body.scrollTop || document.documentElement.scrollTop;

obj.setAttribute("data-fixed",st >= ot?"fixed":"")}

2、面向对象

JS改进,封装成吸顶函数 ceiling.js 方便以后直接Ctrl+C,Ctrl+V

封装方法

/*

* 封装吸顶函数,需结合css实现。

* 也可以直接用js改变样式,可以自行修改。

*/

function ceiling(obj) {

var ot = obj.offsetTop;

document.onscroll = function () {

var st = document.body.scrollTop || document.documentElement.scrollTop;

/*

* 在这里我给obj添加一个自定义属性。className可能会影响原有的class

* 三元运算使代码更简洁

*/

obj.setAttribute("data-fixed",st >= ot?"fixed":"");

}

}

调用方法

window.onload = function () {

/*获取导航对象*/

var wrap = document.getElementById("wrap");

ceiling(wrap) /*调用吸顶函数 */

};

这是最简单版本,欢迎大家在此基础上改进。

延伸

.tab-list[data-fixed="fixed"] {

position: fixed;

top: 0;

left: 0;

margin: 0;

}

function arrCeiling(arr) {

var ot = [];

arr.forEach(function(item, i) {

ot.push(item.offsetTop);

})

document.onscroll = function() {

var st = document.body.scrollTop || document.documentElement.scrollTop;

arr.forEach(function(item, i) {

console.log(st, ot)

item.setAttribute("data-fixed", st >= ot[i] ? "fixed" : "");

})

}

}

window.onload = function() {

/*获取导航数组*/

var arr = document.querySelectorAll('.tab-list')

arrCeiling(arr)

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值