我正在努力清理我的锚的工作方式。我有一个固定在页面顶部的标题,所以当你链接到页面其他地方的锚时,页面跳转,锚位于页面顶部,留下固定标题后面的内容(我希望这是有意义的)。我需要一种方法来抵消锚的25px从头部的高度。我更喜欢HTML或CSS,但Javascript也可以接受。
当前回答
这将从以前的答案中提取许多元素并组合成一个微小的(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);
如果你不喜欢这个动画,替换它
$('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);
其他回答
这对我来说很管用:
[id]::before {
content: '';
display: block;
height: 75px;
margin-top: -75px;
visibility: hidden;
}
你可以只使用CSS而不需要任何javascript。
给你的锚一个类:
<a class="anchor" id="top"></a>
然后,通过将锚定位为块元素并相对定位,您可以将锚定位在比它在页面上实际出现的位置更高或更低的偏移量。-250px将锚点向上定位250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}
这将从以前的答案中提取许多元素并组合成一个微小的(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);
如果你不喜欢这个动画,替换它
$('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);
我遇到了同样的问题,最终手动处理点击事件,如下所示:
$('#mynav a').click(() ->
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 40
}, 200
return false
)
当然,滚动动画是可选的。
你可以使用a[name]:not([href]) css选择器在没有ID的情况下实现这一点。这仅仅是查找有名称且没有href的链接,例如<a name="anc1"></a>
一个示例规则可能是:
a[name]:not([href]){
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
推荐文章
- CSS在特定的“内联块”项之前/之后换行
- 很好的初学者教程socket.io?
- 内嵌CSS有什么不好?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- 我如何删除背景图像在css?
- 如何克服HTML表单嵌套的限制?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导