简体   繁体   English

锚链接直接到锚偏移多个像素?

[英]Anchor link direct to anchor offset by a number of pixels?

I have a webpage which has a floating top navigational bar. 我有一个带有浮动顶部导航栏的网页。 I want to add anchor links to a table of contents to quickly direct to other places on the page. 我想将锚链接添加到目录中,以快速定向到页面上的其他位置。

 #top { display: flex; z-index: 100; background-color: rgba(20, 20, 20, 0.75); position: fixed; top: 0px; margin-left: auto; margin-right: auto; left: 0px; right: 0px; height: 75px; } #bottom { padding-top: 75px; } 
 <div id="top"> &nbsp; </div> <div id="bottom"> <a href='#example'>Click Here</a> <br/> <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> a <br/> <a id='example'></a> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b <br/> b </div> 

When you click "click here", the outcome I'd like is the first "b" (where the anchor leads to) appears underneath the top floating bar. 当您单击“单击此处”时,我想要的结果是第一个“ b”(锚点指向的位置)出现在顶部浮动条下方。 Instead, when you click "click here", it brings the first "b" to the top of the page, hidden by the floating bar. 相反,当您单击“单击此处”时,它将第一个“ b”带到页面顶部,并被浮动条隐藏。

How can I have it such when I click the anchor link, it points to the anchor offset by 75px (for example, if the <a> is 200px from top and I click the anchor link, it'll go to 275px instead of 200px from top)? 当单击锚点链接时,它如何指向锚点偏移量为75px(例如,如果<a>从顶部开始为200px,并且单击锚点链接,它将变为275px而不是200px从顶部)? Is there a no-JS option? 有没有JS选项?

Here you go, this will give you distance - 75px offset 在这里,您将获得距离-75像素偏移

    jQuery(document).ready(function() {
    jQuery("a").on('click', function(event) {
        if (this.hash !== "") {
            // Prevent default anchor click behavior
            event.preventDefault();
            var hash = this.hash;
            jQuery('html, body').animate({
                scrollTop: jQuery(hash).offset().top - 75
            }, 1200, function() {
                window.location.hash = hash;
            });
        } // End if
    });
});

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

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