微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中的使用标签.这是疯狂的,但它应该工作.

原文地址:https://www.jb51.cc/js/153937.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐