溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

原生js如何實現(xiàn)吸頂效果

發(fā)布時間:2021-06-21 12:27:17 來源:億速云 閱讀:221 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)原生js如何實現(xiàn)吸頂效果的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

實現(xiàn)思路如下:

1. div初始居普通文檔流中

2. 給window添加scroll事件(可事件節(jié)流),獲取div的offset的top值,滾動時scrollTop值和top比較,當?shù)竭_top時給div添加一個fixed的class使其固定

3. 向上滾動時當?shù)竭_div初始top時則刪除fixed的class,此時div又回到普通文檔流中

4. fixed樣式非IE6瀏覽器使用position:fixed,IE6使用position:absolute和IE expression

效果圖:

原生js如何實現(xiàn)吸頂效果

代碼如下:

<!doctype html>
<html>
<head>
 <meta charset="utf-8">
 <title>無標題文檔</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }
  #div1 {
   width: 100%;
   height: 50px;
   background: skyblue;
  }
 </style>
 <script>
  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 = '';
   }
  }
 </script>
</head>
<body>
 <div class="all">
  以上<br>
  以上<br>
  以上<br>
  以上<br>
  以上<br>
  以上<br>
  以上<br>
  <div id="div1"></div>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
  啦啦啦啦啦<br>
 </div>
</body>
</html>

感謝各位的閱讀!關(guān)于“原生js如何實現(xiàn)吸頂效果”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI