单击时将按钮切换到扩展导航菜单

时间:2021-05-20 16:10:14

标签: javascript html css

当我单击菜单锚元素时,它会将我带回到页面顶部。当我滚动浏览网站时,我希望菜单停留在我单击菜单锚点时滚动到的部分。我希望菜单锚只充当扩展导航的打开和关闭功能。 [

function openMenu() {
    document.getElementById('menu').style.width = "608px"
    document.getElementById('content').style.marginLeft = "608px"
  }

function closeMenu() {
  document.getElementById('menu').style.width = "0px"
  document.getElementById('content').style.marginLeft = "0px"
}
:root {
      --main-color: #FEFF66;  
      --second-color: #000000;
      --third-color: #FFFFFF;
  }
  * {
    margin: 0;
    padding: 0;
  }
.slide {
  margin: 18px;
  font-size: 25px;
  position: fixed;
}
 .slide a {
    text-decoration: none;
    color: var(--second-color);
    writing-mode: vertical-rl;
    transform: rotate(-180deg);
  }
.help a {
  text-decoration: none;
  color: var(--second-color);
}

.help {
  display: flex;
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: var(--third-color);
  color: var(--second-color);
  overflow: hidden;
}

.links {
  font-size: 40px;
  line-height: 60px;
  padding-top: 14px;
}

.header-menu {
  writing-mode: vertical-rl;
  transform: rotate(-180deg);
  margin: 18px;
  font-size: 25px;
  padding-left: 55px;
}
<section id="header">

  <span class="slide">
      <a href="#" onclick="openMenu()">MENU</a>
    </span>

  <div id="menu" class="help">
    <div><a class="header-menu" href="#" onclick="closeMenu()">MENU</a></div>
    <div class="links">
      <a href="#story">OUR STORY</a><br>
      <a href="#rooms">ROOMS + BOOK</a><br>
      <a href="#neighbourhood">THE NEIGHBOURHOOD</a><br>
      <a href="#art">THE ART</a><br>
      <a href="#faq">FAQ</a>
    </div>
  </div>

</section>

]1

1 个答案:

答案 0 :(得分:1)

在您的点击侦听器中,接收到的事件如下:

<div><a class="header-menu" href="#" onclick="closeMenu($event)">MENU</a></div>

模板中的 $event 在这种情况下具有特殊含义。

然后,在您的 closeMenu 函数上进行相应调整并防止浏览器对锚元素的默认行为。

// Here, the function parameter can be named whatever you like,
// I named it "event" but anything else would work.
function closeMenu(event) {
  // The line below will prevent the default behavior of the browser
  // for this element and event, which means, it scroll to anywhere
  // in this case, nor redirect to another page in case you had a URL
  // in the href attribute.
  event.preventDefault();
  // Your code ...
}