简体   繁体   中英

Modify image href attribute inside an svg element

Inside a function I have an svg object, when I console log it looks like this:

<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>

Now I need to change the href of the image inside the svg element. What i did it so far is set the width svgObject.setAttribute('width', 1000);

But how can I change and select the image element href attribute?

Use setAttributeNS to set the xlink:href attribute as it's in the xlink namespace.

These days some browsers (but not Safari or IE) will let you set the href attribute in the null namespace (which you can do with setAttribute) and will use that in preference to xlink:href but till Safari catches up you're best sticking with 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> 

Try querySelectorAll . It returns a list of elements and then you'll have to pick the first item ( [0] ) of the list.

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

Fiddle

Result: 结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM