如何将变量添加到window.onscroll,使其在某个元素上触发?

时间:2018-06-23 19:56:56

标签: javascript

我使用下面的JS代码将菜单粘贴到页面顶部。这是可行的,但在页面上方触发了约300px。当#stickymenuparent元素位于视口顶部时,如何触发它?

JS:

window.onscroll = function() {myFunction()};

var stickymenuparent = document.getElementById("stickymenuparent");
var sticky = stickymenuparent.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    stickymenuparent.classList.add("sticky")
  } else {
    stickymenuparent.classList.remove("sticky");
  }
}

CSS:

    #stickymenuparent {
    width: 100%;
    height: 100px;
    background: #f0f0f0;
    z-index: 9999;
    box-shadow: 0px 3px 9px 0 #00000017;
    overflow: hidden;
}

.sticky {
    position: fixed;
    top: 0;
    width: 100%;
}

0 个答案:

没有答案