【问题标题】:Modify image href attribute inside an svg element修改 svg 元素内的图像 href 属性
【发布时间】:2018-05-21 14:26:44
【问题描述】:

在函数内部我有一个 svg 对象,当我控制台日志时它看起来像这样:

<svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg" 
     style="overflow: hidden; position: relative;">

  <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc>
  <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
  <path fill="#000000" stroke="#000000" d="M0,0L12,12L12,-12L0,0" transform="matrix(1,0,0,1,0,50)" 
     opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;">
  </path>
  <rect x="0" y="10" width="30" height="80" r="0" rx="0" ry="0" 
    fill="#000000" stroke="#000" opacity="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); opacity: 0;"></rect>
  <image x="134" y="10" width="30" height="80" preserveAspectRatio="none" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    xlink:href="/static/img/pads/numberline/symbols/leftParen.png" 
    style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
  </image>
</svg>

现在我需要更改 svg 元素内图像的 href。 到目前为止我所做的是设置宽度svgObject.setAttribute('width', 1000);

但是如何更改和选择图像元素的 href 属性?

【问题讨论】:

标签: javascript jquery svg


【解决方案1】:

使用setAttributeNS 设置 xlink:href 属性,因为它在 xlink 命名空间中。

如今,一些浏览器(但不是 Safari 或 IE)将允许您在 null 命名空间中设置 href 属性(您可以使用 setAttribute 执行此操作),并且会优先使用该属性而不是 xlink:href,但直到 Safari 赶上您。最好坚持使用 xlink:href

<svg height="100" version="1.1" width="1000" xmlns="http://www.w3.org/2000/svg">

  <image x="134" y="10" width="100" height="100"     xmlns:xlink="http://www.w3.org/1999/xlink" 
    xlink:href="https://bellard.org/bpg/2.png" onclick="this.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'http://pngimg.com/uploads/polar_bear/polar_bear_PNG23514.png')">
  </image>
</svg>

【讨论】:

    【解决方案2】:

    试试querySelectorAll。它返回一个元素列表,然后您必须选择列表的第一项 ([0])。

    document.querySelectorAll("svg image")[0].setAttribute("xlink:href", "myImage.jpg");
    

    Fiddle

    结果:

    【讨论】:

    • 它添加了一个额外的属性xlink:href
    • 这是 Chrome 中的结果:&lt;image x="134" y="10" width="30" height="80" preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="myImage.jpg" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"&gt;
    • 在 chrome 中它按预期工作。您必须查看源代码中的开发人员控制台。它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多