javascript - 替换 <svg> 中的 <use> 元素的属性后单击事件停止工作 (Win7/IE11)

标签 javascript jquery html internet-explorer svg

我们正在使用多个 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);
}

这适用于除 Windows 7 上的 IE10 + IE11 之外的所有浏览器(但奇怪的是它适用于 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 错误吗?我有哪些解决此问题的选择?

最佳答案

是的,这是一个已知的 IE 错误。 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

如果可以,您应该为 CSS 中的 use 标签设置 pointer-events: none;。这很疯狂,但它应该有效。

关于javascript - 替换 <svg> 中的 <use> 元素的属性后单击事件停止工作 (Win7/IE11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29149174/

相关文章:

javascript - 如何将 JS 对象集合发送到 ASP.NET API 服务?

javascript - 如何正确记录通过 Object.defineProperties 添加的实例成员?

javascript - 阻止子 li 可点击,但保留包含 a 的功能

javascript - AJAX 和 php 脚本后添加的表单元素未传输到 $_POST

javascript - Bootstrap 下拉菜单在菜单项上单击添加文本字段

javascript - IE动态图片缓存问题?

javascript - 通过 Javascript 加载 CDN 文件

javascript - PouchDB 检测未同步的文档

jquery - 使用 Cherrypy 和 jQuery/AJAX 从 Python 获取数据

javascript - 独立为同一类的元素设置动画