使锚链接在其链接的上方的某些像素处

dam*_*mon 105 html javascript css anchor

我不确定询问/搜索此问题的最佳方式:

当您单击锚链接时,它会将您带到页面的该部分,其中链接区域现在位于页面的顶部.我想锚链接把我发送到页面的那一部分,但我想在顶部有一些空间.就像在,我不希望它发送给我在非常顶部的链接部分,我想在那里有100个左右像素的空间.

这有意义吗?这可能吗?

编辑显示代码 - 它只是一个锚标记:

<a href="#anchor">Click me!</a>

<p id="anchor">I should be 100px below where I currently am!</p>
Run Code Online (Sandbox Code Playgroud)

Eri*_*son 134

window.addEventListener("hashchange", function () {
    window.scrollTo(window.scrollX, window.scrollY - 100);
});
Run Code Online (Sandbox Code Playgroud)

这将允许浏览器为我们跳转到锚点的工作,然后我们将使用该位置来抵消.

编辑1:

正如@erb所指出的那样,只有在更改哈希值的同时在页面上才有效.输入#something已包含在URL中的页面不适用于上述代码.这是另一个处理它的版本:

// The function actually applying the offset
function offsetAnchor() {
    if(location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
Run Code Online (Sandbox Code Playgroud)

注:要使用jQuery,你可以只更换window.addEventListener$(window).on的例子.谢谢@Neon.

编辑2:

正如少数人所指出的,如果你连续两次或多次点击相同的锚链接,上述情况将会失败,因为没有hashchange强制偏移的事件.

这个解决方案是@Mave建议的略微修改版本,并使用jQuery选择器来简化

// The function actually applying the offset
function offsetAnchor() {
  if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
  }
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
  // Click events are captured before hashchanges. Timeout
  // causes offsetAnchor to be called after the page jump.
  window.setTimeout(function() {
    offsetAnchor();
  }, 0);
});

// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
Run Code Online (Sandbox Code Playgroud)

这个例子的JSFiddle就在这里

  • 谢谢@erb.OP的问题不需要这个案例,但为了帮助其他人,我添加了另一个版本的实现. (7认同)
  • 仍然缺少一个小细节.如果单击一个锚点,然后向上滚动然后再次单击相同的锚点,没有hashchange,因此它不会使用偏移量.想法? (2认同)
  • 不需要jQuery - 只需替换`$(window).on("hashchange",```window.addEventListener("hashchange",` (2认同)

小智 75

只使用css,你可以为锚定元素添加填充(如上面的解决方案)为了避免不必要的空格,你可以添加相同高度的负边距:

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}
Run Code Online (Sandbox Code Playgroud)

我不确定这在任何情况下是否是最佳解决方案,但它对我来说效果很好.

  • 你可以使用`position:relative` css属性做同样的事情.所以,它就像`position:relative; 顶部:-50px;` (10认同)
  • 如果在它之上50px之内有一个链接,它可能会被覆盖并且我认为无法点击 (3认同)

use*_*091 66

这是 2020 年的答案:

#anchor {
  scroll-margin-top: 100px;
}
Run Code Online (Sandbox Code Playgroud)

因为它得到了广泛的支持

  • 略低于 90% 的浏览器(包括带有scroll-snap-margin-top 的 iOS)应该足以选择退出 JavaScript 解决方案,特别是如果用户影响只是需要滚动的话。但是,嘿,在这种方法伤害别人之前,让我们否决它吧。 (9认同)
  • 这样一个简单而有效的答案。很快就会达到 100% 支持(对于现代浏览器)。 (3认同)
  • 我建议 [`scroll-padding`](https://caniuse.com/?search=scroll-padding) 而不是 [`scroll-margin`](https://caniuse.com/?search=scroll-margin) )因为 Safari 根据 caniuse.com 使用非标准名称 `scroll-snap-margin` (2认同)

小智 54

更好的解决方案:

<p style="position:relative;">
    <a name="anchor" style="position:absolute; top:-100px;"></a>
    I should be 100px below where I currently am!
</p>
Run Code Online (Sandbox Code Playgroud)

只需将<a>标记定位在相对定位的对象内部即可.

进入页面或通过页面内的哈希更改时工作.

  • 我更喜欢你的解决方案,因为它不使用javascript.谢谢! (3认同)
  • 对于bootstrap固定顶部导航栏非常有用 (3认同)

小智 16

最佳方案

<span class="anchor" id="section1"></span>
<div class="section"></div>

<span class="anchor" id="section2"></span>
<div class="section"></div>

<span class="anchor" id="section3"></span>
<div class="section"></div>

<style>
.anchor{
  display: block;
  height: 115px; /*same height as header*/
  margin-top: -115px; /*same height as header*/
  visibility: hidden;
}
</style>
Run Code Online (Sandbox Code Playgroud)

  • 为什么这是最好的解决方案?此外,如果您给出一定程度的解释/推理答案,它会更有帮助. (8认同)

muh*_*uha 12

这个纯 CSS 解决方案适合我。

:target:before {
content:"";
display:block;
height:90px; /* fixed header height*/
margin:-90px 0 0; /* negative fixed header height */
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到它 - > https://www.wikitechy.com/tutorials/javascript/offsetting-an-html-anchor-to-adjust-for-fixed-header

这是一个小提琴: https: //jsfiddle.net/e8o2p3az/


M K*_*M K 9

这将在没有jQuery和页面加载的情况下工作.

(function() {
    if (document.location.hash) {
        setTimeout(function() {
            window.scrollTo(window.scrollX, window.scrollY - 100);
        }, 10);
    }
})();
Run Code Online (Sandbox Code Playgroud)


小智 6

试试这个代码,点击链接时它已经有一个平滑的动画。

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top - 100
    }, 500);
});
Run Code Online (Sandbox Code Playgroud)


小智 5

This should work:

    $(document).ready(function () {
    $('a').on('click', function (e) {
        // e.preventDefault();

        var target = this.hash,
            $target = $(target);

       $('html, body').stop().animate({
        'scrollTop': $target.offset().top-49
    }, 900, 'swing', function () {
    });

        console.log(window.location);

        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

Just change the .top-49 to what fits with your anchor link.