[英]Is there a way to dynamically set y attribute for an image element inside svg element?
[英]Modify image href attribute inside an svg element
在函数内部,我有一个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属性?
使用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>
尝试使用querySelectorAll 。 它返回一个元素列表,然后您必须选择列表的第一项( [0]
)。
document.querySelectorAll("svg image")[0].setAttribute("xlink:href", "myImage.jpg");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.