粘性菜单/导航,固定菜单后框阴影不起作用

时间:2018-10-06 11:10:19

标签: javascript html css html5

我当前的菜单/导航存在此问题,当菜单固定后,框阴影消失(带有边框的东西)。但是,当菜单不再固定时,它将返回。除此之外,菜单还可以正常工作。

const nav = document.querySelector("#navigation");
const navTop = nav.offsetTop;

window.addEventListener("scroll", stickyNavigation);

function stickyNavigation() {
  if (window.scrollY >= navTop) {
    nav.classList.add("fixed-nav");

    console.log("sticky!!");
  } else {
    nav.classList.remove("fixed-nav");
  }
}
nav {
  display: flex;
  align-items: flex-start;
  flex-wrap: nowrap;
  height: 100%;
  width: 100vw;
  /* border-bottom: 3px solid #f341cc; */
  box-shadow: 0px 3px #f341cc;
}

nav a {
  padding: 30px;
  background-color: black;
  text-decoration: none;
  color: #f341cc;
  font-size: 2em;
  font-family: "Varela Round", sans-serif;
  text-align: center;
  width: 40%;
  flex-grow: 1;
  text-decoration: none;
}


/* ---- sticky menu --- */

.fixed-nav {
  position: fixed;
  top: 0;
  /*box-shadow: 0px 3px #f341cc;*/
  z-index: 1;
}

body {
  height: 200vh;
}
<nav id="navigation">
  <a href="">something</a>
  <a href="">something</a>
  <a href="">something</a>
</nav>

2 个答案:

答案 0 :(得分:2)

height: 100%中删除nav。当元素变为fixed时,它可能使用主体作为位置父级,而height: 100%成为整个屏幕,从而将阴影和边框推出屏幕。

示例:

const nav = document.querySelector("#navigation");
const navTop = nav.offsetTop;

window.addEventListener("scroll", stickyNavigation);

function stickyNavigation() {
  if (window.scrollY >= navTop) {
    nav.classList.add("fixed-nav");

    console.log("sticky!!");
  } else {
    nav.classList.remove("fixed-nav");
  }
}
nav {
  display: flex;
  align-items: flex-start;
  flex-wrap: nowrap;
  /* remove - height: 100%; */
  width: 100vw;
  /* border-bottom: 3px solid #f341cc; */
  box-shadow: 0px 3px #f341cc;
}

nav a {
  padding: 30px;
  background-color: black;
  text-decoration: none;
  color: #f341cc;
  font-size: 2em;
  font-family: "Varela Round", sans-serif;
  text-align: center;
  width: 40%;
  flex-grow: 1;
  text-decoration: none;
}


/* ---- sticky menu --- */

.fixed-nav {
  position: fixed;
  top: 0;
  /*box-shadow: 0px 3px #f341cc;*/
  z-index: 1;
}

body {
  height: 200vh;
}
<nav id="navigation">
  <a href="">something</a>
  <a href="">something</a>
  <a href="">something</a>
</nav>

如果非固定位置需要height: 100%,则可以使用:not()伪类:

nav:not(.fixed-nav) {
    height: 100%;
}

答案 1 :(得分:0)

从此处移出高度100%

nav {
    display: flex;
    align-items: flex-start;
    flex-wrap: nowrap;
    /* height: 100%; // Delete this */
    width: 100vw;
    /* border-bottom: 3px solid #f341cc; */
    box-shadow: 0px 3px #f341cc;
}