javascript - $ (':target' ) 在 Internet Explorer 11 中返回长度 0

标签 javascript jquery internet-explorer-11

我正在尝试补偿网页中 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/

相关文章:

javascript - 使用 getFieldDecorator 正确设置 Antd DatePicker 初始值

jquery .html() 函数会杀死其他一切

css - 如何为 IE 11 编写 CSS hack?

Angular 8 项目无法在 Microsoft Edge 和 IE11 中运行

javascript - 在 shiny 中,是否可以根据客户端 Web 浏览器输入更新输入选择?

javascript - 没有输入时如何更改过滤器操作?

javascript - activeClassName 不适用于可变路径的 react 路由器

jquery - iPad:Mobile Safari、HTML5 <video> 和 jquery 转换

jquery - 将 Bootstrap 3.3.6 升级到 4.0.0 后出现错误 $(...).modal 不是 angularjs 中的函数

Internet Explorer 中的 CSS "unset"/"initial"