javascript – 在(Win7 / IE11)中替换元素的属性后点击事件停止工作

我们正在使用多个 svg symbols显示图标.
<!-- defining them at the start of the page -->
<div id="icon-container">
<svg xmlns="http://www.w3.org/2000/svg">
    <symbol xmlns="http://www.w3.org/2000/svg"
            id="rect" ...>
        <rect... />
    </symbol>

    <symbol xmlns="http://www.w3.org/2000/svg"
            id="circle" ...>
        <circle... />
    </symbol>
</svg>
</div>

<!-- using them in the page somewhere -->
<svg>
    <use xlink:href="#rect"></use>
</svg>

在某些情况下,我们需要稍后再更换一个图标(如在崩溃控件上),因此我创建了一个帮助函数来将xlink:href更改为新的符号名称.

$.fn.replaceSVGIcon = function(id) {
    $(this).find('svg')
           .andSelf()
           .filter('svg')
           .find('use')
           .attr('xlink:href','#' + id);
}

这可以在每个浏览器中工作,除了IE7 IE11在Windows 7(但奇怪的是,它适用于Windows 8).

当您在IE11中打开下面的代码片段并单击红色框时,一切都很好,但一旦您开始点击元素,就会在图标第一次更改之后打破整个页面.

(function($){
    $.fn.replaceSVGIcon = function(id) {
        $(this).find('svg').andSelf().filter('svg').find('use').attr('xlink:href','#' + id);
    }
})(jQuery);

clickFunction = function() {
    var $elem = $('#icon');
    
    if ($elem.find('use').attr('xlink:href') == '#rect')
    {
        $elem.replaceSVGIcon('circle');
    } else {
        $elem.replaceSVGIcon('rect');
    }
};
#icon-container {
    visibility: collapse;
    display: none;
}

#icon {
    height: 40px;
    width: 40px;
    fill: #454545;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="icon-container">
    <svg xmlns="http://www.w3.org/2000/svg">
        <symbol xmlns="http://www.w3.org/2000/svg" id="rect" viewBox="0 0 50 50">
            <rect x="15" y="15" width="20" height="20"></rect>
        </symbol>
    
        <symbol xmlns="http://www.w3.org/2000/svg" id="circle" viewBox="0 0 50 50">
            <circle cx="25" cy="25" r="10"></circle>
        </symbol>
    </svg>
</div>

<svg id="icon" onclick="clickFunction()">
    <rect fill="red" height="40" width="40"></rect>
    <use xlink:href="#rect"></use>
</svg>

为什么会发生这种情况,这是一个已知的Internet Explorer bug?解决这个问题我有什么选择?

解决方法

是的,这是一个已知的IE bug. https://connect.microsoft.com/IE/feedback/details/796745/mouse-events-are-not-delivered-at-all-anymore-when-inside-an-svg-a-use-is-removed-from-the-dom

如果可以的话,你应该设置指针事件:none;为CSS中的使用标签.这是疯狂的,但它应该工作.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...