让锚链接去一些像素以上的地方,它的链接

我不确定问/寻找这个问题的最佳方式:

当你点击一个锚链接时,它会把你带到页面的那一部分,链接到的区域现在位于页面的顶部。我希望锚链接发送我到该页面的一部分,但我想在顶部的一些空间。因为,我不希望它发送给我的链接-与它在非常顶部的一部分,我希望100像素左右的空间有。

这说得通吗? 这可能吗?

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

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


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

要链接到一个元素,然后使用纯 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 小提琴演示。

使用普通的 JavaScript 方法:

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


window.addEventListener('hashchange', addMargin);

JS 小提琴演示。

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

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

编辑1:

正如@erb 所指出的那样,只有当哈希被更改时您正在页面上时,这种方法才有效。使用已经在 URL 中的 #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即可

编辑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 是 给你

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

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

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

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

我不确定这是否是最好的解决方案,但它对我来说很好。

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

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

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

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

只要您的 HREF 锚标记没有指定 NAME 属性,这就可以工作

最佳解决方案

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

更好的解决办法是:

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

只需将 <a>标签放置在相对定位的对象内部,并进行绝对定位即可。

在输入页面或通过页面内的散列更改时工作。

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

这应该会奏效:

    $(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改成适合你的锚链接就可以了。

我知道这有点晚了,但是我发现了一些非常重要的东西,如果您正在使用 Bootstrap 的 Scrollspit,那么可以在代码中添加它们。(http://getbootstrap.com/javascript/#scrollspy)

这让我抓狂了好几个小时。

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

  1. 滚动时获得奇怪的闪烁效果
  2. 你会发现,当你点击锚,你会在该部分的土地,但滚动间谍将假定你是它上面的一个部分。

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

埃里克的回答很棒,但你真的不需要那个暂停。如果您正在使用 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();
});

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

最简单的解决办法是:

CSS

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

超文本标示语言

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

基于@Eric Olson 的 解决方案只需要稍微修改一下就可以包含我想要特别提到的锚元素

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

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

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


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

我也有同样的问题。我已经定位了导航,我要吴哥窟从导航下面开始。window.addEventListener...的解决方案不适合我,因为我设置我的页面是 scroll-behavior:smooth,所以它设置偏移 取而代之滚动到吴哥。如果 setTimeout()工作的时间是足够滚动到底,但它仍然看起来不好。所以我的解决方案是在吴哥窟中加入一个假定的绝对 div,使用 height:[the height of the nav]bottom:100%。在这个例子中,这个 div 在吴哥元素的顶部结束,并且从你要滚动到的吴哥元素的位置开始。现在我要做的就是将吴哥窟链接设置为这个绝对的 div,然后完成:)

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

我面临着类似的问题,我解决了使用以下代码

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

Thomas 的解决方案的一个变体: CSS 元素 > 元素 选择器在这里很方便:

CSS

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

超文本标示语言

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


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

点击链接会将滚动位置移动到100px 以上的任何地方的元素与类 paddedAnchor的位置。

支持在非 IE 浏览器,并在 IE 版本9。为了支持 IE7和 IE8,必须声明一个 <!DOCTYPE>

我自己找到了一个简单的解决办法。 有一个15像素的边距顶部

超文本标示语言

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

CSS

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

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

CSS

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

超文本标示语言

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

这样说吧:

.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>";
}

以下是2020年的答案:

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

因为 得到了广泛的支持

我也遇到过同样的问题,有一个真正快速简单的解决方案,不需要 CSS 的 JS。只需创建一个单独的未样式化 div,其 ID 类似于“ aboutMeAnchor”,并将其放置在您实际想要着陆的区域的上方。

这也是一个很好的解决方案。像这样在目标 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*/
}

我尝试做一些类似的事情,最后我的工作是添加伪元素 ::before到你想要滚动到的 div。这将在元素之前添加一个空白空间,锚链接将滚动到这个空白空间的顶部。例如:

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

这个纯 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

这是一把小提琴: Https://jsfiddle.net/e8o2p3az/

我发现了一个令人惊讶的解决方案,我认为基本上是同样的问题,关于滚动的锚链接的目标位置。

我有一个页面,它显示了一个很长的文档,其中有一些小节,我在它们的标题上面放了一个书签 dom 元素,就像这样:

<div class = "TB_BookMark"
id = "someId"
></div>
<h3 class="TB">Section 1</h3>

其思想是,用户可以通过单击侧面窗格中的链接导航到文档的子部分。第一个这样的链接应该滚动窗口到页面的开始。注意,上面的 bookmark-div 的内容是空的,这意味着它不应该占用页面的空间,因此导航到第一个链接应该导航到页面的开头。

问题在于,单击第一个链接会滚动页面,这样第一个部分标题就会立即出现在可见区域的顶部,上面没有空格。换句话说,页面从顶部向下滚动了一点。然而,当加载或重新加载页面时,在第一节标题上方有(也应该是)一个可见的空白边距。

我相信这和最初的问题描述的是同一个问题。似乎没有办法让第一个链接滚动到页面的最开始。

问题是加载页面时看到的内容与单击第一个链接时看到的内容不同。如果在第一个页眉上面不再有空白边缘,或者在加载或重新加载页面时空白边缘太大,那么它看起来就不太好。

我让它工作的方法是这样的 CSS:

.TB_Bookmark
{ border:solid 0px    Transparent;  /* Does NOT do what I want. */
border:solid 0.01px Transparent;  /* Does what I want. */
}


h3.TB
{ margin-top:12px;
margin-bottom:12px;
}


body
{ margin-top: 0px;
}

除了第一个边框定义,上面所有的都是需要让它工作,我离开作为一个例子,什么不工作。当然,第二个边界定义覆盖了第一个,因此生效。

为什么“ orders: Solid 0.01 px;”可以工作,但是“ orders: Solid 0px;”我不明白。0和0.01之间不应该有很大的差异,对吗?这个解决方案可以同时在 Chrome 和 Firefox 上工作,如果我使用“ orders: solid0px;”,它们就会停止工作。