我正在尝试调整网页中锚点的位置,以避免其被固定标题覆盖。
我通过这个答案解决了这个问题,对于除IE之外的所有浏览器都可以正常工作。 但在IE中,它只是在锚点移动后向上滚动了几个像素。
代码如下:
(function($, window) {
var adjustAnchor = function() {
var $anchor = $(':target'),
fixedElementHeight = 160;
console.log("Anchor: "+ JSON.stringify($anchor));
if ($anchor.length > 0) {
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
}
};
$(window).on('hashchange load', function() {
adjustAnchor();
});
})(jQuery, window);
现在,在IE11中console.log的输出如下:
{
"length": 0,
"prevObject": {
"0": {
"__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
"_html5shiv": 1,
"jQuery1111049273906621767055": 4
},
"context": {
"__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
"_html5shiv": 1,
"jQuery1111049273906621767055": 4
},
"length": 1
},
"context": {
"__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR": false,
"_html5shiv": 1,
"jQuery1111049273906621767055": 4
},
"selector": ":target"
}
问题显然在于 "length": 0, 这意味着没有选择任何内容。为什么会这样呢?:target 选择器在 IE11 中应该可以正常工作,但 jQuery 没有抓取它。
请原谅我对 jQuery 的无知和我的糟糕英语。
var $anchor = $(':target'),
改成var $anchor = $(window.location.hash),
吗? - epascarello{"context":{"jQuery111107266217162832618":4},"selector":"#condiciones"}
。 - David Prieto