简体   繁体   中英

How to change the href of this SVG sprite using vanilla JavaScript?

I am using an SVG sprite sheet and I am trying to change the href of the svg using vanilla javascript, but after researching a solution, have run into a brick wall.

html

 let scores, roundScore, activePlayer, dice, diceSvg, diceImg, diceHrefString; scores = [0,0]; roundScore = 0; activePlayer = 0; document.querySelector(`#p${activePlayer}c-score`).textContent = dice; diceSvg = document.getElementById("dice-icon"); diceSvg.style.display = "none"; document.getElementById("roll-dice").addEventListener("click",function(){ dice = Math.floor(Math.random() * 6) + 1; diceImg = document.querySelector(".dice-icon"); diceHrefString = `dice_sprite_sheet.svg#dice-${dice}`; if(dice !== 0){ diceImg.setAttributeNS("xlink:","href",diceHrefString); }else{ diceImg.setAttributeNS("xlink:","href","dice"); } diceSvg.style.display = "block"; }); 
 <svg class="dice-icon" id="dice-icon"> <use xlink:href="dice_sprite_sheet.svg#dice"></use> </svg> 

As I've commented: you need to use the svg xlink namespace: http://www.w3.org/1999/xlink . When you change the value of the xlink:href dynamically this is how you do it: theUse.setAttributeNS(SVG_XLINK, 'xlink:href', '#theId');

This is an example:

 const SVG_XLINK = "http://www.w3.org/1999/xlink"; theUse.setAttributeNS(SVG_XLINK, 'xlink:href', '#spade'); 
 svg{border:1px solid} 
 <svg class="dice-icon" id="dice-icon" viewBox="0 0 20 20" width="200" height="200"> <use id="theUse" xlink:href="#heart"></use> </svg> <svg width="0" height="0" display="none"> <title>symbols defs</title> <defs> <symbol viewBox="0 0 20 20" id="spade" style="overflow: visible"> <title>Spade</title> <path d="M9,15C9,20 0,21 0,16S6,9 10,0C14,9 20,11 20,16 S11,20 11,15Q11,20 13,20H7Q9,20 9,15Z"/> </symbol> <symbol viewBox="0 0 20 20" id="heart" style="overflow: visible"> <title>heart</title> <path d="M10,6 Q10,0 15,0T20,6Q20,10 15,14 T10,20Q10,18 5,14T0,6Q0,0 5,0T10,6Z"/> </symbol> </defs> </svg> 

I hope it helps.

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