HTML+CSS+js代码搞定导航吸顶效果

2023-05-0808:35:36WEB前端开发Comments1,141 views字数 1547阅读模式

一、HTML布局

首先写HTML布局文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html

<body>
<div id="wrap"></div>
</body>

二、CSS样式

给点简单的样式文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html

    <style>
    *{
          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;
    }
    </style>

三、JS代码

1、面向过程

直接编写5行代码搞定文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html

<script>
    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":"")}
</script>

2、面向对象

JS改进,封装成吸顶函数 ceiling.js 方便以后直接Ctrl+C,Ctrl+V文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html

封装方法
/* 
 * 封装吸顶函数,需结合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":"");
        }
    }
调用方法
<script src="ceiling.js"></script>
<script>
    window.onload = function () {
         /*获取导航对象*/
        var wrap = document.getElementById("wrap");
        ceiling(wrap) /*调用吸顶函数  */
    };
</script>

这是最简单版本,欢迎大家在此基础上改进。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html

延伸

.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)
};
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/38787.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/38787.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定