JS 實現DIV 滾動至頂部后固定


JS 實現DIV 滾動至頂部后固定

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="UTF-8">
  <title>DIV滾動至頂部后固定</title>
</head>
<body style="height:2000px;">
<div style="height: 200px"></div>
<div id="nav_keleyi_com" style="position:relative;top:0;background:#00f;width:100px; height:100px">
  Test Div
</div>
<script type="text/javascript">
  function menuFixed(id) {
    var obj = document.getElementById(id);
    var _getHeight = obj.offsetTop;

    window.onscroll = function () {
      changePos(id, _getHeight);
    }
  }

  function changePos(id, height) {
    var obj = document.getElementById(id);
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop < height) {
      obj.style.position = 'relative';
    } else {
      obj.style.position = 'fixed';
    }
  }
  window.onload = function () {
    menuFixed('nav_keleyi_com');
  }
</script>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM