在Internet Explorer 11中,$(':target')返回长度为0。

4

我正在尝试调整网页中锚点的位置,以避免其被固定标题覆盖。

我通过这个答案解决了这个问题,对于除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
@epascarello,如果$anchor没有长度属性,则向上滚动将无法工作。现在$anchor的内容是这样的{"context":{"jQuery111107266217162832618":4},"selector":"#condiciones"} - David Prieto
1个回答

2

我通过在锚点的目标位置添加id属性,来解决了这个问题,像这样:

<a class="anchor" name="condiciones" id="condiciones"></a> 

由于某些原因,在所有浏览器中,name属性足以使锚点起作用,但为了在Internet Explorer中使用jQuery抓取它们,必须使用id属性来创建锚点。

我讨厌IE。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接