Mat*_*den 1056 html javascript css anchor offset
我正在努力清理锚点的工作方式.我有一个固定在页面的顶部的头,所以当你在页面的其他地方链接到一个锚,页面跳转所以其锚固在页面的顶部,留下固定头后面的内容(我希望那讲得通).我需要一种方法来将锚点从头部的高度偏移25px.我更喜欢HTML或CSS,但Javascript也可以接受.
Jan*_*Jan 1133
您可以在没有任何JavaScript的情况下使用CSS.
给你的锚一个班:
<a class="anchor" id="top"></a>
Run Code Online (Sandbox Code Playgroud)
然后,您可以将锚点设置为高于或低于页面实际显示位置的偏移量,方法是将其设置为块元素并相对定位.-250px将锚定位置为250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*vin 322
我找到了这个解决方案
<a name="myanchor">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>
Run Code Online (Sandbox Code Playgroud)
这不会在内容中产生任何差距,并且锚链接工作非常好.
Ian*_*ark 159
由于这是演示的关注点,纯CSS解决方案将是理想的.然而,这个问题是在2012年提出的,尽管已经提出了相对定位/负边际解决方案,但这些方法看起来相当笨拙,产生了潜在的流量问题,并且无法动态响应DOM /视口的变化.
考虑到这一点,我相信使用JavaScript 仍然是(2017年2月)最好的方法.下面是一个vanilla-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);
Run Code Online (Sandbox Code Playgroud)
Hrv*_*jak 148
我也在寻找解决方案.在我的情况下,这很容易.
我有一个包含所有链接的列表菜单:
<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>
Run Code Online (Sandbox Code Playgroud)
在它下面应该去的标题下面.
<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>
Run Code Online (Sandbox Code Playgroud)
现在,因为我的页面顶部有一个固定的菜单,我不能让它转到我的标签,因为它会在菜单后面.
相反,我在我的标记中添加了一个带有正确id的span标记.
<h3><span id="one"></span>one</h3>
Run Code Online (Sandbox Code Playgroud)
现在使用2行css来正确定位它们.
h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}
Run Code Online (Sandbox Code Playgroud)
更改顶部值以匹配固定标题的高度(或更多).现在我假设这也适用于其他元素.
Mar*_*ham 108
FWIW这对我有用:
[id]::before {
content: '';
display: block;
height: 75px;
margin-top: -75px;
visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)
Zia*_*iav 85
受亚历山大·萨文启发的纯css解决方案:
a[name] {
padding-top: 40px;
margin-top: -40px;
display: inline-block; /* required for webkit browsers */
}
Run Code Online (Sandbox Code Playgroud)
(可选)如果目标仍在屏幕外,您可能需要添加以下内容:
vertical-align: top;
Run Code Online (Sandbox Code Playgroud)
Lan*_*nce 38
这需要从以前的答案中获取许多元素,并将其组合成一个微小的(194字节缩小的)匿名jQuery函数.调整fixedElementHeight以获取菜单或阻止元素的高度.
(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);
Run Code Online (Sandbox Code Playgroud)
如果您不喜欢动画,请替换
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
Run Code Online (Sandbox Code Playgroud)
有:
window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
Run Code Online (Sandbox Code Playgroud)
Uglified版本:
!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);
Run Code Online (Sandbox Code Playgroud)
Lez*_*ezz 34
我的解决方案结合了CMS的目标和选择器之前.其他技术不考虑锚中的文本.将高度和负边距调整为您需要的偏移量...
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}
Run Code Online (Sandbox Code Playgroud)
Sho*_*vik 30
我一直面临着类似的问题,不幸的是,在实施了上述所有解决方案之后,我得出了以下结论.
我写了这个简单的滚动js,它解释了由于标题引起的偏移并将div重新定位在大约125像素以下.请根据需要使用它.
HTML
<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
Run Code Online (Sandbox Code Playgroud)
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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
Ale*_*one 30
对于现代浏览器,只需将CSS3:target选择器添加到页面即可.这将自动应用于所有锚点.
:target {
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)
Zso*_*gyi 28
a[id]::before {
content: '';
display: block;
height: 50px;
margin: -30px 0 0;
}
Run Code Online (Sandbox Code Playgroud)
这将在每个具有id的a-tag之前附加一个伪元素.调整值以匹配标题的高度.
Kri*_*aun 11
正如@moeffju所说,这可以通过CSS实现.我遇到的问题(我很惊讶,我还没有看到过讨论)是将前面的元素与填充或透明边框重叠的技巧,可以防止在这些部分底部的悬停和点击操作,因为下面的部分更高Z顺序.
我找到的最佳解决方案是将部分内容放在以下div位置z-index: 1:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
use*_*125 10
具有改变位置属性的解决方案并不总是可行的(它可以破坏布局)因此我建议:
HTML:
<a id="top">Anchor</a>
Run Code Online (Sandbox Code Playgroud)
CSS:
#top {
margin-top: -250px;
padding-top: 250px;
}
Run Code Online (Sandbox Code Playgroud)
用这个:
<a id="top"> </a>
Run Code Online (Sandbox Code Playgroud)
最小化重叠,并将font-size设置为1px.空锚在某些浏览器中不起作用.
对于同样的问题,我使用了一个简单的解决方案:在每个锚点上放置一个40px的填充顶部.
小智 8
从这个链接给出的答案中借用一些代码(没有指定作者),你可以在锚点上包含一个漂亮的平滑滚动效果,同时使它停在锚点上方-60px处,很好地适应固定的引导程序导航bar(需要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(){
});
});
Run Code Online (Sandbox Code Playgroud)
不要使用与页面其余内容重叠的固定位置导航栏(整个页面主体可滚动),而是考虑使用带有静态导航栏的不可滚动主体,然后将页面内容放在下面绝对定位的可滚动 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>
Run Code Online (Sandbox Code Playgroud)
...CSS 像这样:
.static-navbar {
height: 100px;
}
.scrollable-content {
position: absolute;
top: 100px;
bottom: 0;
overflow-y: scroll;
width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
然而,这种方法有一个显着的缺点,即当页面标题中的元素获得焦点时,用户将无法使用键盘滚动页面(例如,通过向上和向下箭头或 Page Up 和 Page Up 和向下翻页键)。
| 归档时间: |
|
| 查看次数: |
513363 次 |
| 最近记录: |