我正在尝试补偿网页中 anchor 的移动位置,使其不被固定标题覆盖。
我用这个 anwser 解决了这个问题, 它适用于除 IE 之外的所有浏览器。它只是在 anchor 移动后向上滚动几个像素。
代码如下:
(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"
}
问题显然是“长度”:0,这意味着没有选择任何东西。为什么是这样? :target 选择器在 IE11 中应该可以正常工作,但 jQuery 无法抓取它。
请原谅我对 jQuery 的无知和我糟糕的英语。
最佳答案
我通过将 name 属性旁边的 id 属性添加到 anchor 的目标来解决这个问题,如下所示:
<a class="anchor" name="condiciones" id="condiciones"></a>
出于某种原因,name 属性足以让 anchor 在每个浏览器中工作,但为了在 Internet Explorer 中使用 jQuery 抓取它们,必须使用 id 属性制作 anchor 。
我讨厌 IE。
关于javascript - $ (':target' ) 在 Internet Explorer 11 中返回长度 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496423/