【问题标题】:Using AppendChild on an svg in Internet Explorer is doing the wrong thing在 Internet Explorer 中的 svg 上使用 AppendChild 是错误的
【发布时间】:2019-06-02 20:21:34
【问题描述】:

我遇到了这个 gem 的问题:

function CmdRefresh(cmd) {
    var svg = document.createElement('svg');
    svg.setAttribute("viewBox", "0 0 3200 1800");
    svg.setAttribute("width", window.innerWidth);
    svg.setAttribute("height", window.innerHeight);
    var x = 160;
    for (var i = 0; i < cmd.Cards.length; i++) {
        var suit = Math.floor(cmd.Cards[i] / 13);
        var rank = cmd.Cards[i] % 13;
        var card = "CDHS"[suit] + "A23456789TJQK"[rank];

        var img = document.createElement('image')
        img.setAttribute("width", 505);
        img.setAttribute("height", 707);
        img.setAttribute("x", x + i * 225);
        img.setAttribute("y", 676);
        img.setAttribute("href", "/img/Card_" + card + ".svg");

        svg.appendChild(img);
    }
    document.body.innerHTML = svg.outerHTML;
}

我特意在这个项目中坚持使用原生 JavaScript。它在 Chrome 中运行良好。我在输出中得到了这个:

<svg viewBox="0 0 3200 1800" width="1920" height="551">
    <image width="505" height="707" x="160" y="676" href="/img/Card_C9.svg"></image>
    <image width="505" height="707" x="385" y="676" href="/img/Card_D3.svg"></image>
    ....
</svg>

这是我所期望的(我省略了大部分 image 标签)。它在 Edge 中不起作用。 Edge 将“image”转换为“img”,但失败了。此错误已于 2016 年 8 月得到确认,但仍未修复。 (https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8545675/) 我再次尝试使用 Internet Explorer,显示如下:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3200 1800" width="1920" height="911"></svg>
<img width="505" height="707" x="160" y="676" href="/img/Card_C9.svg" />
....

但在 Internet Explorer 中编辑标签会显示这一点(滚动查看未包含子项的结束标签):

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 3200 1800" width="1920" height="911" />

显然这个标签不能有子标签。这里有什么解决方案?说“搞砸”来使用 createElement() 等?我犯错了吗?微软又做了一个吗?谁能给我一个线索?

【问题讨论】:

    标签: javascript google-chrome internet-explorer svg microsoft-edge


    【解决方案1】:

    您不能使用 createElement 在资源管理器中创建 SVG 元素,您必须使用 createElementNS 即

    document.createElementNS('http://www.w3.org/2000/svg', 'svg')
    

    对于 svg 元素,以及

    document.createElementNS('http://www.w3.org/2000/svg', 'image')
    

    用于图像元素。

    在 Explorer 时代,它们都以这种方式工作,即 createElement 仅适用于 HTML 元素。很多人都犯了这个错误,以至于较新的浏览器已经调整 createElement 以在 SVG 文档中创建 SVG 元素并在 HTML 文档中创建 HTML 元素,而不是总是创建 HTML 元素。

    Explorer 还将要求您使用 setAttributeNS 方法在 xlink 命名空间中创建 href 属性。

    img.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "/img/Card_" + card + ".svg");
    

    最后我希望资源管理器不支持使用 innerHTML 来创建 SVG 元素,您需要简单地使用 appendChild 附加您的 SVG,即使在现代浏览器中也会更有效,因为您避免将所有内容序列化为字符串和再次回来。类似的东西

    document.body.appendChild(svg);
    

    【讨论】:

    • 啊哈!这就说得通了。虽然我知道 innerHTML 行不通,但我还是屈服于将 SVG 视为 HTML 而不是 XML 的诱惑。我回家后会试一试。这也可能绕过 Edge 的 img/image 错误。
    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2018-12-16
    • 1970-01-01
    • 2015-11-27
    • 2014-08-24
    相关资源
    最近更新 更多