實現思路如下:
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
效果圖:

代碼如下:
<!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>以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答