【问题标题】:Anchor link direct to anchor offset by a number of pixels?锚链接直接到锚偏移多个像素?
【发布时间】:2017-07-21 07:43:16
【问题描述】:

我有一个带有浮动顶部导航栏的网页。我想在目录中添加锚链接以快速指向页面上的其他位置。

#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>

当您单击“单击此处”时,我想要的结果是第一个“b”(锚点指向的位置)出现在顶部浮动条下方。相反,当您单击“单击此处”时,它会将第一个“b”带到页面顶部,并被浮动条隐藏。

当我点击锚链接时,我怎么能得到它,它指向偏移75px的锚(例如,如果&lt;a&gt;距离顶部200px,我点击锚链接,它将转到275px而不是距离顶部 200 像素)?有没有无 JS 选项?

【问题讨论】:

    标签: html css anchor


    【解决方案1】:

    给你,这会给你距离 - 75px 偏移

        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
        });
    });
    

    【讨论】:

    • 在所有 CSS 都失败后想尝试一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 2019-08-09
    • 2020-03-02
    • 1970-01-01
    • 2019-11-06
    • 2023-01-12
    相关资源
    最近更新 更多