5行js代碼搞定導航吸頂效果

1、HTML佈局

首先寫HTML佈局css

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

2、CSS樣式

給點簡單的樣式git

<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>

3、JS代碼

一、面向過程

直接編寫5行代碼搞定github

<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>

二、面向對象

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

調用方法

<script src="ceiling.js"></script>
<script>
    window.onload = function () {
         /*獲取導航對象*/
        var wrap = document.getElementById("wrap");
        ceiling(wrap) /*調用吸頂函數  */
    };
</script>

這是最簡單版本,歡迎你們在此基礎上改進。函數

延伸

.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)
};

案例:
5行js代碼搞定導航吸頂效果佈局

相關文章
相關標籤/搜索