为什么平滑滚动不起作用? (JS)

时间:2019-01-29 17:45:30

标签: javascript scroll header

我有这段代码(从教程开始,谢谢Sysleaf),使标题在滚动时出现和消失。它应该很平滑,但不幸的是并非如此。我已经在浏览器中启用了它。此外,所有内容均可在教程的演示中使用。

CSS:

  header {
  background-color: rgb(46, 49, 94);
  border-color: rgb(17, 27, 39);
  position: fixed;
  height:120px; 
  width: 100%;
  z-index: 1;
  top: 0;
      }

.header-pin {
  transform: translateY(0);
}

.header-unpin {
  transform: translateY(-65px); 
}

和JS:

let currentScrollY = 0;
let lastKnownScrollY = 0;
let ticking = false;
let idOfHeader = 'header';
let eleHeader = null;
const classes = {
  pinned: 'header-pin',
  unpinned: 'header-unpin',
};

function onScroll() {
  currentScrollY = window.pageYOffset;
  requestTick();
}  

function requestTick() {
  if (!ticking) {
    requestAnimationFrame(update);
  }
  ticking = true;
}

function update() {
  if (currentScrollY < lastKnownScrollY) {
    pin();
  } else if (currentScrollY > lastKnownScrollY) {
    unpin();
  }
  lastKnownScrollY = currentScrollY;
  ticking = false;
};

function pin() {
  if (eleHeader.classList.contains(classes.unpinned)) {
    eleHeader.classList.remove(classes.unpinned);
    eleHeader.classList.add(classes.pinned);
  }
}

function unpin() {
  if (eleHeader.classList.contains(classes.pinned) || !eleHeader.classList.contains(classes.unpinned)) {
    eleHeader.classList.remove(classes.pinned);
    eleHeader.classList.add(classes.unpinned);
  }
}

window.onload = function() {
  eleHeader = document.getElementById(idOfHeader);
  document.addEventListener('scroll', onScroll, false)
}

请,您能帮我告诉我出什么事了吗?

0 个答案:

没有答案