如何使页眉粘在滚动上

时间:2018-09-17 09:35:50

标签: html bootstrap-4

当用户滚动时,如何使标题保持粘性?

链接:https://colorlib.com/preview/theme/coinbuzz/coinbuzz/index3.html

1 个答案:

答案 0 :(得分:0)

尝试一下 风格:

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
.sticky + .content {
  padding-top: 102px;
}

脚本:

window.onscroll = function() {myFunction()};
var header = document.getElementById("myHeader");
var sticky = header.offsetTop;
function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}

HTML正文:

<div class="header" id="myHeader">
  <h2>My Header</h2>
</div>

这应该为您工作