我使用下面的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%;
}