偏移 HTML 锚点以针对固定标头进行调整
offsetting an html anchor to adjust for fixed header
我正在尝试清理我的锚点的工作方式。我有一个固定在页面顶部的标题,因此当您链接到页面中其他位置的锚点时,页面会跳转,因此锚点位于页面顶部,将内容留在固定标题后面(我希望这是有意义的)。 我需要一种方法将锚点从标题的高度偏移 25px。我更喜欢HTML或CSS,但Javascript也是可以接受的。
你可以只使用CSS,没有任何javascript。
给你的定位点一个类:
<a class="anchor" id="top"></a>
然后,您可以将锚点定位在比它在页面上实际显示的位置更高或更低,方法是将其设置为块元素并相对定位它。 -250px 会将锚点向上定位 250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}
我找到了这个解决方案:
<a name="myanchor">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>
这不会在内容中产生任何差距,锚链接效果非常好。
FWIW 这对我有用:
[id]::before {
content: '';
display: block;
height: 75px;
margin-top: -75px;
visibility: hidden;
}
在寻找解决这个问题的方法。就我而言,这很容易。
我有一个包含所有链接的列表菜单:
<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>
下面是它应该去的标题。
<h3>one</h3>
<p>text here</p>
<h3>two</h3>
<p>text here</p>
<h3>three</h3>
<p>text here</p>
<h3>four</h3>
<p>text here</p>
现在,因为我的页面顶部有一个固定的菜单,所以我不能让它转到我的标签,因为这会在菜单后面。
相反,我在标签中放置了一个具有正确 id 的 span 标签。
<h3><span id="one"></span>one</h3>
现在使用 2 行 CSS 来正确定位它们。
h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}
更改顶部值以匹配固定标头的高度(或更多)。现在我认为这也适用于其他元素。
由于这是演示的问题,因此纯CSS解决方案将是理想的选择。然而,这个问题是在 2012 年提出的,尽管已经提出了相对定位/负裕量解决方案,但这些方法似乎相当笨拙,会产生潜在的流程问题,并且无法动态响应 DOM/视口的变化。
考虑到这一点,我相信使用JavaScript仍然是(2017年2月)最好的方法。下面是一个普通的 JS 解决方案,它将响应锚点点击并在加载时解析页面哈希(请参阅 JSFiddle)。如果需要动态计算,请修改 .getFixedOffset()
方法。如果您使用的是jQuery,这里有一个经过修改的解决方案,具有更好的事件委派和平滑滚动。
(function(document, history, location) {
var HISTORY_SUPPORT = !!(history && history.pushState);
var anchorScrolls = {
ANCHOR_REGEX: /^#[^ ]+$/,
OFFSET_HEIGHT_PX: 50,
/**
* Establish events, and fix initial scroll position if a hash is provided.
*/
init: function() {
this.scrollToCurrent();
window.addEventListener('hashchange', this.scrollToCurrent.bind(this));
document.body.addEventListener('click', this.delegateAnchors.bind(this));
},
/**
* Return the offset amount to deduct from the normal scroll position.
* Modify as appropriate to allow for dynamic calculations
*/
getFixedOffset: function() {
return this.OFFSET_HEIGHT_PX;
},
/**
* If the provided href is an anchor which resolves to an element on the
* page, scroll to it.
* @param {String} href
* @return {Boolean} - Was the href an anchor.
*/
scrollIfAnchor: function(href, pushToHistory) {
var match, rect, anchorOffset;
if(!this.ANCHOR_REGEX.test(href)) {
return false;
}
match = document.getElementById(href.slice(1));
if(match) {
rect = match.getBoundingClientRect();
anchorOffset = window.pageYOffset + rect.top - this.getFixedOffset();
window.scrollTo(window.pageXOffset, anchorOffset);
// Add the state to history as-per normal anchor links
if(HISTORY_SUPPORT && pushToHistory) {
history.pushState({}, document.title, location.pathname + href);
}
}
return !!match;
},
/**
* Attempt to scroll to the current location's hash.
*/
scrollToCurrent: function() {
this.scrollIfAnchor(window.location.hash);
},
/**
* If the click event's target was an anchor, fix the scroll position.
*/
delegateAnchors: function(e) {
var elem = e.target;
if(
elem.nodeName === 'A' &&
this.scrollIfAnchor(elem.getAttribute('href'), true)
) {
e.preventDefault();
}
}
};
window.addEventListener(
'DOMContentLoaded', anchorScrolls.init.bind(anchorScrolls)
);
})(window.document, window.history, window.location);
受Alexander Savin启发的纯css解决方案:
a[name] {
padding-top: 40px;
margin-top: -40px;
display: inline-block; /* required for webkit browsers */
}
(可选)如果目标仍在屏幕之外,您可能需要添加以下内容:
vertical-align: top;
我的解决方案结合了 CMS 的目标和之前选择器。其他技术不考虑锚点中的文本。将高度和负边距调整到您需要的偏移量...
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}
这从以前的答案中获取了许多元素,并组合成一个微小的(缩小了 194 字节)匿名 jQuery 函数。 根据菜单或阻塞元素的高度调整固定元素高度。
(function($, window) {
var adjustAnchor = function() {
var $anchor = $(':target'),
fixedElementHeight = 100;
if ($anchor.length > 0) {
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
}
};
$(window).on('hashchange load', function() {
adjustAnchor();
});
})(jQuery, window);
如果您不喜欢动画,请替换
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
跟:
window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
优格化版本:
!function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);
对于现代浏览器,只需将 CSS3 :target 选择器添加到页面即可。这将自动应用于所有定位点。
:target {
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
你可以在没有js的情况下做到这一点,也不需要改变html。它是仅限 css 的。
a[id]::before {
content: '';
display: block;
height: 50px;
margin: -30px 0 0;
}
这将在每个带有 id 的 a 标签之前附加一个伪元素。 调整值以匹配标题的高度。
我一直面临类似的问题,不幸的是,在实施上述所有解决方案后,我得出了以下结论。
- 我的内部元素有一个脆弱的CSS结构,实现一个位置相对/绝对游戏,完全破坏了页面设计。
- CSS不是我的强项。
我写了这个简单的滚动 js,它解释了由于标题引起的偏移量,并将div 重新定位在下方约 125 像素处。请根据需要使用它。
该目录
<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
JavaScript
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^'//,'') == this.pathname.replace(/^'//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offset height of header here too.
}, 1000);
return false;
}
}
});
在此处查看实时实现。
对于同一个问题,我使用了一个简单的解决方案:在每个锚点上放置一个 40px 的填充顶部。
正如@moeffju所建议的,这可以通过CSS来实现。我遇到的问题(我很惊讶我没有看到讨论过)是用填充或透明边框重叠以前的元素的技巧,可以防止在这些部分底部悬停和单击操作,因为下一个在 z 顺序中更高。
我发现的最佳解决方法是将部分内容放在z-index: 1
的div
中:
// Apply to elements that serve as anchors
.offset-anchor {
border-top: 75px solid transparent;
margin: -75px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
position: relative;
z-index: 1;
}
具有更改位置属性的解决方案并不总是可行的(它可以破坏布局),因此我建议这样做:
.HTML:
<a id="top">Anchor</a>
.CSS:
#top {
margin-top: -250px;
padding-top: 250px;
}
使用这个:
<a id="top"> </a>
以尽量减少重叠,并将字体大小设置为 1px。空锚点在某些浏览器中不起作用。
借用此链接给出的答案中的一些代码(未指定作者),您可以为锚点添加漂亮的平滑滚动效果,同时使其停在锚点上方的 -60px,非常适合固定引导导航栏下方(需要 jQuery):
$(".dropdown-menu a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 60
}, 300, function(){
});
});
如果您的锚点是表元素或在表(行或单元格)内,则上述方法效果不佳。
我必须使用 javascript 并绑定到窗口hashchange
事件来解决此问题(演示):
function moveUnderNav() {
var $el, h = window.location.hash;
if (h) {
$el = $(h);
if ($el.length && $el.closest('table').length) {
$('body').scrollTop( $el.closest('table, tr').position().top - 26 );
}
}
}
$(window)
.load(function () {
moveUnderNav();
})
.on('hashchange', function () {
moveUnderNav();
});
* 注意:哈希更改事件并非在所有浏览器中都可用。
与其使用由页面其余内容(整个页面正文可滚动)置于固定位置的导航栏之下,不如考虑使用带有静态导航栏的不可滚动正文,然后将页面内容放在下面绝对位置的可滚动div 中。
也就是说,有这样的 HTML...
<div class="static-navbar">NAVBAR</div>
<div class="scrollable-content">
<p>Bla bla bla</p>
<p>Yadda yadda yadda</p>
<p>Mary had a little lamb</p>
<h2 id="stuff-i-want-to-link-to">Stuff</h2>
<p>More nonsense</p>
</div>
。和像这样的 CSS:
.static-navbar {
height: 100px;
}
.scrollable-content {
position: absolute;
top: 100px;
bottom: 0;
overflow-y: scroll;
width: 100%;
}
然而,这种方法有一个明显的缺点,那就是当页面标题中的元素被聚焦时,用户将无法使用键盘滚动页面(例如,通过向上和向下箭头或向上翻页和向下翻页键)。
下面是一个 JSFiddle 演示了这一点。
a[name]:not([href])
css 选择器在没有 ID 的情况下实现此目的。这只是查找带有名称但没有 href 的链接,例如 <a name="anc1"></a>
示例规则可能是:
a[name]:not([href]){
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
这是受到 Shouvik 的回答的启发 - 与他的概念相同,只是固定标头的大小没有硬编码。只要您的固定标头位于第一个标头节点中,这应该"正常工作"
/*jslint browser: true, plusplus: true, regexp: true */
function anchorScroll(fragment) {
"use strict";
var amount, ttarget;
amount = $('header').height();
ttarget = $('#' + fragment);
$('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
return false;
}
function outsideToHash() {
"use strict";
var fragment;
if (window.location.hash) {
fragment = window.location.hash.substring(1);
anchorScroll(fragment);
}
}
function insideToHash(nnode) {
"use strict";
var fragment;
fragment = $(nnode).attr('href').substring(1);
anchorScroll(fragment);
}
$(document).ready(function () {
"use strict";
$("a[href^='#']").bind('click', function () {insideToHash(this); });
outsideToHash();
});
我在 TYPO3 网站中遇到了这个问题,其中所有"内容元素"都用以下内容包装:
<div id="c1234" class="contentElement">...</div>
我更改了渲染,使其呈现如下:
<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>
而这个 CSS:
.anchor{
position: relative;
top: -50px;
}
固定的顶栏高 40px,现在锚点再次工作并在顶栏下开始 10px。
这种技术的唯一缺点是你不能再使用:target
。
除了Ziav的回答(感谢Alexander Savin),我需要使用老式<a name="...">...</a>
,因为我们在代码中将<div id="...">...</div>
用于其他目的。我在使用display: inline-block
时遇到了一些显示问题 - 每个<p>
元素的第一行都略微右缩进(在Webkit和Firefox浏览器上)。我最终尝试了其他display
价值观,display: table-caption
非常适合我。
.anchor {
padding-top: 60px;
margin-top: -60px;
display: table-caption;
}
我在每个h1
元素之前添加了 40px 高度的.vspace
元素,该元素保持锚点。
<div class="vspace" id="gherkin"></div>
<div class="page-header">
<h1>Gherkin</h1>
</div>
在 CSS 中:
.vspace { height: 40px;}
它工作得很好,空间不会窒息。
带有可链接 ID 的隐藏 span 标记如何提供导航栏的高度:
#head1 {
padding-top: 60px;
height: 0px;
visibility: hidden;
}
<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>
这是小提琴:http://jsfiddle.net/N6f2f/7
您还可以使用关注属性添加锚点:
(text-indent:-99999px;)
visibility: hidden;
position:absolute;
top:-80px;
并为父容器提供一个相对位置。
对我来说很完美。
@Jan的优秀答案的另一个转折是将其合并到使用 jQuery(或 MooTools)的 #uberbar 固定标头中。(http://davidwalsh.name/persistent-header-opacity)
我已经调整了代码,因此内容的顶部始终位于固定标题下方而不是下方,并且还再次添加了@Jan锚点,以确保锚点始终位于固定标题下方。
CSS:
#uberbar {
border-bottom:1px solid #0000cc;
position:fixed;
top:0;
left:0;
z-index:2000;
width:100%;
}
a.anchor {
display: block;
position: relative;
visibility: hidden;
}
jQuery(包括对 #uberbar 和锚点方法的调整):
<script type="text/javascript">
$(document).ready(function() {
(function() {
//settings
var fadeSpeed = 200, fadeTo = 0.85, topDistance = 30;
var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
var inside = false;
//do
$(window).scroll(function() {
position = $(window).scrollTop();
if(position > topDistance && !inside) {
//add events
topbarML();
$('#uberbar').bind('mouseenter',topbarME);
$('#uberbar').bind('mouseleave',topbarML);
inside = true;
}
else if (position < topDistance){
topbarME();
$('#uberbar').unbind('mouseenter',topbarME);
$('#uberbar').unbind('mouseleave',topbarML);
inside = false;
}
});
$('#content').css({'margin-top': $('#uberbar').outerHeight(true)});
$('a.anchor').css({'top': - $('#uberbar').outerHeight(true)});
})();
});
</script>
最后是 HTML:
<div id="uberbar">
<!--CONTENT OF FIXED HEADER-->
</div>
....
<div id="content">
<!--MAIN CONTENT-->
....
<a class="anchor" id="anchor1"></a>
....
<a class="anchor" id="anchor2"></a>
....
</div>
也许这对喜欢 #uberbar 衰落的 dixed 标题的人很有用!
@AlexanderSavin的解决方案对我来说在WebKit
浏览器中效果很好。
我还必须使用:target伪类,它将样式应用于选定的锚点以调整FF
,Opera
和IE9
中的填充:
a:target {
padding-top: 40px
}
请注意,这种风格不适用于Chrome
/Safari
,因此您可能必须使用css-hacks,条件注释等。
另外,我想注意到亚历山大的解决方案之所以有效,是因为目标元素是inline
的。如果您不想要链接,您可以简单地更改display
属性:
<div id="myanchor" style="display: inline">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>
这是我们在网站上使用的解决方案。将 headerHeight
变量调整为标题高度。将 js-scroll
类添加到应在单击时滚动的锚点。
// SCROLL ON CLICK
// ---------------------------------------------------------------------
$('.js-scroll').click(function(){
var headerHeight = 60;
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight;
}, 500);
return false;
});
我遇到了同样的问题,最终手动处理了点击事件,例如:
$('#mynav a').click(() ->
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 40
}, 200
return false
)
当然,滚动动画是可选的。
- 加载图像后调整HTML画布的大小
- 根据窗口大小调整 HTML 中 SVG 图像的大小
- 使用src调整HTML Iframe的大小我可以't控制
- 根据屏幕大小自动调整HTML按钮的大小
- 如何在手机上调整 html 页面的大小
- 如何动态调整html文本框的大小以避免溢出
- 网页大小自动调整HTML简单
- D3和Select未正确调整Html布局
- 使用javascript调整HTML多个全宽视频的大小
- 使用jQuery调整HTML表列的大小
- 如何调整html<画布>动态使用Javascript
- 如何调整HTML元素的高度以覆盖其所有可用空间'的父级
- 使用javascript调整html画布的大小
- 如何根据浏览器窗口大小动态调整html表
- HTML标签调整HTML元素的大小
- 使用触摸调整HTML元素的大小
- 用javascript调整html表td的大小
- 调整html表列的大小
- 使用Jquery调整Html表的行和列大小
- 如何使用jquery重新调整html表的行和列的大小