我正在尝试使标题折叠

时间:2019-02-15 13:59:35

标签: javascript html css

我试图在向下滚动时更改标题

html:

<div id="header" class="head"> </div>

css:

.head {
    width:100%;
    height: 70px;
    background-color: black;
}
.sticky {
    position: fixed !important;
    height: 40px;
    top: 0;
    width: 100%;
 }

js:

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

由于某种原因它无法正常工作,任何人都可以帮忙!?!?

1 个答案:

答案 0 :(得分:0)

var header = document.getElementById('header');
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add('sticky');
  } else {
    header.classList.remove('sticky');
  }
}

window.addEventListener('scroll', myFunction);
body {
  background: red;
  height: 800px;
}

.head {
  width: 100%;
  height: 70px;
  background-color: black;
}

.sticky {
  background: yellow;
  position: fixed !important;
  height: 40px;
  top: 0;
  width: 100%;
}
<div id="header" class="head"></div>