通过使用scrollTop()使用jquery实现浮动菜单

问题描述 投票:0回答:1

我是 jquery 的新手,昨天我尝试用 jquery 制作自己的浮动菜单,因为我无法使用 css 获得满意的结果。但我写的代码没有运行。你们能告诉我我做错了什么吗?

我想要做的是,当我下降几个像素时,菜单应该重新出现并保持在顶部。

这是我正在使用的 jquery 代码:-

var menu = function(){
    var x=$(body).scrollTop();
    if(x>10){
        $('header').animate({position:fixed},100);
    }
    else{
        $('header').animate({position:static},100);
    }
}

$(document).ready(menu);
jquery html css jquery-ui menu
1个回答
0
投票

您不一定需要 jQuery 来完成该任务。
监听

"scroll"
"resize"
事件名称,并在满足条件时在 #menu 上切换课程 (
y > 10
)。
我将在此演示中使用 100px:

const elMenu = document.querySelector("#menu");

const handleMenu = () => {
  const { scrollY } = window;
  elMenu.classList.toggle("sticky", scrollY > 100);
};

addEventListener("resize", handleMenu);
addEventListener("scroll", handleMenu);
handleMenu();
/*QuickReset*/ * { margin: 0; box-sizing: border-box; }

body{
  height: 300vh;
  border: dashed #000;
  border-width: 0 4px 0 4px;
}

#menu {
  position: relative;
  background: orange;
  padding: 2rem;
  
  &.sticky {
    position: sticky;
    width: 100%;
    top: 0px;
  }
}
<nav id="menu">
  #menu will reappear after 100px scroll
</nav>

© www.soinside.com 2019 - 2024. All rights reserved.