Html 使锚链接在链接到的位置上方一些像素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17534661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:53:03  来源:igfitidea点击:

Make anchor link go some pixels above where it's linked to

javascripthtmlcssanchor

提问by damon

I'm not sure the best way to ask/search for this question:

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

When you click on an anchor link, it brings you to that section of the page with the linked-to area now at the VERY TOP of the page. I would like the anchor link to send me to that part of the page, but I would like some space at the top. As in, I don't want it to send me to the linked-to part with it at the VERY TOP, I would like 100 or so pixels of space there.

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

Does this make sense? Is this possible?

这有意义吗?这可能吗?

Edited to show code - it's just an anchor tag:

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

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

<p id="anchor">I should be 100px below where I currently am!</p>

回答by Eric Olson

window.addEventListener("hashchange", function () {
    window.scrollTo(window.scrollX, window.scrollY - 100);
});

This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.

这将允许浏览器为我们完成跳转到锚点的工作,然后我们将使用该位置进行偏移。

EDIT 1:

编辑 1:

As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a #somethingalready in the URL does not work with the above code. Here is another version to handle that:

正如@erb 所指出的,这仅在更改哈希时您在页面上时才有效。使用#somethingURL 中已有的进入页面不适用于上述代码。这是处理该问题的另一个版本:

// 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).

NOTE: To use jQuery, you could just replace window.addEventListenerwith $(window).onin the examples. Thanks @Neon.

注意:要使用 jQuery,您可以将示例中的window.addEventListenerwith替换为$(window).on。谢谢@霓虹灯。

EDIT 2:

编辑2:

As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no hashchangeevent to force the offset.

正如一些人所指出的,如果您连续两次或多次单击同一个锚链接,上述操作将失败,因为没有hashchange事件强制偏移。

This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity

此解决方案是@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);

JSFiddle for this example is here

此示例的 JSFiddle在这里

回答by user3364768

Working only with css you can add a padding to the anchored element (as in a solution above) To avoid unnecessary whitespace you can add a negative margin of the same height:

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

#anchor {
    padding-top: 50px;
    margin-top: -50px;
}

I am not sure if this is the best solution in any case, but it works fine for me.

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

回答by Thomas

Even better solution:

更好的解决方案:

<p style="position:relative;">
    <a name="anchor" style="position:absolute; top:-100px;"></a>
    I should be 100px below where I currently am!
</p>

Just position the <a>tag with absolute positioning inside of a relatively positioned object.

只需在<a>相对定位的对象内使用绝对定位来定位标签。

Works when entering the page or through a hash change within page.

在进入页面或通过页面内的哈希更改时有效。

回答by Никита Андрейчук

Best Solution

最佳解决方案

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

回答by user127091

Here's the 2020 answer for this:

这是 2020 年的答案:

#anchor {
  scroll-margin-top: 100px;
}

Because it's widely supported!

因为它得到了广泛的支持

回答by M K

This will work without jQuery and on page load.

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

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

回答by David says reinstate Monica

To link to an element, and then 'position' that element an arbitrary distance from the top of the page, using pure CSS, you'd have to use padding-top, that way the element is still positioned at the top of the window, but it appears, visibly, to be positioned some distance from the top of the view-port, for example:

要链接到一个元素,然后使用纯 CSS 将该元素“定位”到距页面顶部任意距离的位置,您必须使用padding-top,这样元素仍然位于窗口的顶部,但它看起来,明显地,位于距视口顶部一定距离的位置,例如:

<a href="#link1">Link one</a>
<a href="#link2">Link two</a>

<div id="link1">
    The first.
</div>

<div id="link2">
    The second.
</div>

CSS:

CSS:

div {
    /* just to force height, and window-scrolling to get to the elements.
       Irrelevant to the demo, really */
    margin-top: 1000px;
    height: 1000px;
}

#link2 {
    /* places the contents of the element 100px from the top of the view-port */
    padding-top: 100px;
}

JS Fiddle demo.

JS小提琴演示

To use a plain JavaScript approach:

要使用纯 JavaScript 方法:

function addMargin() {
    window.scrollTo(0, window.pageYOffset - 100);
}

window.addEventListener('hashchange', addMargin);

JS Fiddle demo.

JS小提琴演示

回答by dMehta

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

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

只需将 .top-49 更改为适合您的锚链接的内容即可。

回答by rppc

Eric's answer is great, but you really don't need that timeout. If you're using jQuery, you can just wait for the page to load. So I'd suggest changing the code to:

埃里克的回答很好,但你真的不需要超时。如果您使用的是 jQuery,则只需等待页面加载即可。所以我建议将代码更改为:

// 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).on("hashchange", function () {
    offsetAnchor();
});

// Let the page finish loading.
$(document).ready(function() {
    offsetAnchor();
});

This also gets us rid of that arbitrary factor.

这也让我们摆脱了那个随意的因素。

回答by Mespr

If you use explicit anchor names such as,

如果您使用显式锚点名称,例如,

<a name="sectionLink"></a>
<h1>Section<h1>

then in css you can simply set

然后在 css 中你可以简单地设置

A[name] {
    padding-top:100px;
}

This will work as long as your HREF anchor tags don't also specify a NAME attribute

只要您的 HREF 锚标记不指定 NAME 属性,这就会起作用