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

时间:2013-07-08 19:42:57

标签: javascript html css anchor

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

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

这有意义吗?这可能吗?

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

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

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

25 个答案:

答案 0 :(得分:123)

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

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

编辑1:

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

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

注: 要使用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);

这个例子的JSFiddle是here

答案 1 :(得分:71)

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

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

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

答案 2 :(得分:51)

更好的解决方案:

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

只需将<a>标记与绝对定位放在相对定位的对象内。

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

答案 3 :(得分:34)

这是2020年的答案:

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

因为it's widely supported

答案 4 :(得分: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>

答案 5 :(得分:9)

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

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

答案 6 :(得分:4)

要链接到一个元素,然后使用纯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:

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

使用纯JavaScript方法:

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

window.addEventListener('hashchange', addMargin);

JS Fiddle demo

答案 7 :(得分:3)

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

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

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

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

只要您的HREF锚标记不指定NAME属性

,这将有效

答案 8 :(得分:3)

这应该有效:

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

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

答案 9 :(得分:3)

Eric的答案很棒,但你真的不需要超时。如果你正在使用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();
});

这也让我们摆脱了这个任意因素。

答案 10 :(得分:2)

尝试此代码,点击链接时已经有了平滑的动画。

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

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

答案 11 :(得分:1)

最简单的解决方案:

CSS

#link {
    top:-120px; /* -(some pixels above) */
    position:relative;
    z-index:5;
}

HTML

<body>
    <a href="#link">Link</a>
    <div>
        <div id="link"></div> /*this div should placed inside a target div in the page*/
        text
        text
        text
    <div>
</body>

答案 12 :(得分:1)

我刚刚为自己找到了一个简单的解决方案。 边距顶端为15px

HTML

<h2 id="Anchor">Anchor</h2>

CSS

h2{margin-top:-60px; padding-top:75px;}

答案 13 :(得分:1)

Thomas解决方案的一种变体:CSS element>element selectors在这里很方便:

CSS

.paddedAnchor{
  position: relative;
}
.paddedAnchor > a{
  position: absolute;
  top: -100px;
}

HTML

<a href="#myAnchor">Click Me!</a>

<span class="paddedAnchor"><a name="myAnchor"></a></span>

点击链接会将滚动位置移动到位置为paddedAnchor的元素上方的100px。

在非IE浏览器和版本9的IE中均受支持。要在IE 7和8中获得支持,必须声明<!DOCTYPE>

答案 14 :(得分:0)

将此样式设置为:

.hash_link_tag{margin-top: -50px; position: absolute;}

并在链接之前在单独的div标签中使用此类,例如:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

或将此PHP代码用于echo链接标记:

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

答案 15 :(得分:0)

这个纯 CSS 解决方案对我有用。

:target:before {
content:"";
display:block;
height:90px; /* fixed header height*/
margin:-90px 0 0; /* negative fixed header height */
}

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

答案 16 :(得分:0)

我也遇到了同样的问题,并且有一个非常快速简单的解决方案,没有JS CSS。只需创建一个ID为“ aboutMeAnchor”的单独的无样式div,然后将其放置在您实际要停留的部分上方即可。

答案 17 :(得分:0)

这也是一个很好的解决方案。像这样在目标 div 上方制作一个 div 并将 a 链接到这个 div;

<div class="destination" id="link"></div> /**Needs to be above the destination**/

.destination {
    position:absolute;
    z-index:-1;
    left:0;
    margin-top:-100px;/* height of nav*/
}

答案 18 :(得分:0)

我试图做类似的事情,最终对我有用的是将伪元素 ::before 添加到要滚动到的 div。这将在元素之前添加一个空白区域,并且锚链接将滚动到该空白区域的顶部。例如:

#anchor::before {
  content: "";
  display: block;
  height: 60px;
}

答案 19 :(得分:0)

仅使用css,之前没有覆盖和不可点击的内容没有问题(这是指针事件:无):

CSS

.anchored::before {
    content: '';
    display: block;
    position: relative;
    width: 0;
    height: 100px;
    margin-top: -100px;
}

HTML

<a href="#anchor">Click me!</a>
<div style="pointer-events:none;">
<p id="anchor" class="anchored">I should be 100px below where I currently am!</p>
</div>

答案 20 :(得分:0)

我遇到了类似的问题,我通过使用以下代码解决了

$(document).on('click', 'a.page-scroll', function(event) {
        var $anchor = $(this);
        var desiredHeight = $(window).height() - 577;
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - desiredHeight
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });

答案 21 :(得分:0)

我遇到同样的问题。我有一个导航假设像素,我希望吴哥在导航下开始。 window.addEventListener...的解决方案对我不起作用,因为我将页面设置为scroll-behavior:smooth,因此它设置偏移而不是滚动到angkor。 setTimeout()工作如果时间足够滚动到结尾,但仍然看起来不太好。所以我的解决方案是在angkor中添加一个假定的绝对div,height:[the height of the nav]bottom:100%。在这种情况下,这个div在angkor元素的顶部结束,并从你要滚动到的吴哥的位置开始。现在我所做的就是设置这个绝对div的角度和完成的工作:)

&#13;
&#13;
html,body{
    margin:0;
    padding:0;
    scroll-behavior:smooth;
}

nav {
    height:30px;
    width:100%;
    font-size:20pt;
    text-align:center;
    color:white;
    background-color:black;
    position:relative;
}

#my_nav{
    position:fixed;
    z-index:3;
}
#fixer_nav{
    position:static;
}

#angkor{
    position:absolute;
    bottom:100%;
    height:30px;
}
&#13;
<nav id="my_nav"><a href="#angkor">fixed position nav<a/></nav>
<nav id="fixer_nav"></nav>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.
</p>

<nav><div id="angkor"></div>The angkor</nav>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec lacus vel eros rutrum volutpat. Cras ultrices enim sit amet odio dictum, eget consectetur mi pellentesque. Sed mollis gravida nulla, eu euismod turpis efficitur id. Integer pretium posuere fringilla. Aenean laoreet, augue non pharetra elementum, lectus massa congue orci, a imperdiet neque enim ut dui. Praesent commodo orci bibendum leo suscipit viverra. Nunc fermentum semper eleifend. Pellentesque suscipit nulla aliquet, egestas lectus sed, egestas dui. Vivamus scelerisque maximus nibh, ac dignissim nunc tempor a. Praesent facilisis non lacus et aliquam. Proin ultricies lacus vitae nibh ullamcorper gravida. Proin elit arcu, convallis eget posuere quis, placerat id augue. Fusce ex risus, tempus nec orci vitae, feugiat faucibus quam. Integer risus metus, ornare et rhoncus vitae, accumsan a urna.

</p>
&#13;
&#13;
&#13;

答案 22 :(得分:0)

基于@Eric Olson solution只需稍微修改一下就可以包含我想要特效的锚元素

// Function that actually set offset
function offsetAnchor(e) {
    // location.hash.length different to 0 to ignore empty anchor (domain.me/page#)
    if (location.hash.length !== 0) {
        // Get the Y position of the element you want to go and place an offset
        window.scrollTo(0, $(e.target.hash).position().top - 150);
    }
}

// Catch the event with a time out to perform the offset function properly
$(document).on('click', 'a[href^="#"]', function (e) {
    window.setTimeout(function () {
        // Send event to get the target id later
        offsetAnchor(e);
    }, 10);
});

答案 23 :(得分:0)

我知道这有点晚了,但如果您使用的是Bootstrap的Scrollspy,我发现在您的代码中放入一些非常重要的内容。 (http://getbootstrap.com/javascript/#scrollspy

这让我疯了好几个小时。

滚动间谍的偏移量必须与window.scrollY匹配,否则你将面临以下风险:

  1. 滚动时获得奇怪的闪烁效果
  2. 你会发现当你点击锚点时,你会落在那个部分,但滚动间谍会认为你是它上面的一个部分。
  3. &#13;
    &#13;
     var body = $('body');
        body.scrollspy({
            'target': '#nav',
            'offset': 100 //this must match the window.scrollY below or you'll have a bad time mmkay
    });
    
    $(window).on("hashchange", function () {
            window.scrollTo(window.scrollX, window.scrollY - 100);
    });
    &#13;
    &#13;
    &#13;

答案 24 :(得分:-1)

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

<div style="margin-top: -100px; padding-top: 100px;" id="anchor"></div>
<p>I should be 100px below where I currently am!</p>