简体   繁体   English

当菜单的 class 名称不是“xxx”时,我想链接到锚点下方的 go 50px

[英]I want link to go 50px below anchor when class name of the menu is not "xxx"

I have a top menu inside a div that contains anchor links, like this:我在包含锚链接的 div 中有一个顶部菜单,如下所示:

 <div id="menu">
   <ul>
     <li>
       <a href="#item1">ITEM 1</a>
     </li>
     <li>
       <a href="#item2">ITEM 2</a>
     </li>
     <li>
       <a href="#item3">ITEM 3</a>
     </li>
   </ul>
 </div>

When I scroll down the website, a class "wrapfixed" is automatically added on scroll by javascript to make the menu sticky, it becomes like this:当我向下滚动网站时,javascript 会在滚动时自动添加一个 class “wrapfixed”,以使菜单具有粘性,它变成这样:

<div id="menu" class="wrapfixed">...</div>

I would like the link to go 50px below the anchor, when the class "wrapfixed" is NOT there.当 class “wrapfixed”不存在时,我想要指向 go 50px 锚点下方的链接。

how do you do that?你是怎样做的?

Thank you谢谢

To achieve this you will want to to prevent the default link behavior of # links.要实现这一点,您需要阻止 # 链接的默认链接行为。 Then check the if the links parent menu has the wrapfixed class, so you can set the extra padding.然后检查链接父菜单是否有wrapfixed class,这样您就可以设置额外的填充。 Before using window.ScrollTo to scroll the page to the right location.在使用window.ScrollTo之前将页面滚动到正确的位置。

Someting like this should work for you:像这样的东西应该适合你:

function scrollToLinks(){
    var links = document.querySelectorAll("a");
    for (let i=0, len=links.length; i < links.length; i++) {
      links[i].addEventListener("click", function(event) {
        event.preventDefault();
        const index = event.target.href.indexOf('#');
        const selector = event.target.href.substring(index);
        const target = document.querySelector(selector);
        const box = target.getBoundingClientRect();
        const padding = event.target.parentNode.parentNode.parentNode.classList.contains('wrapfixed') ? 50 : 0;
        const y = box.top + padding;
        window.scrollTo(0, y);
      })
    }
}
window.addEventListener("load", scrollToLinks);

And here is a working demo on Codepen这是Codepen 上的工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM