繁体   English   中英

如何使用香草JavaScript更改此SVG精灵的href?

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

我正在使用SVG Sprite表,并且尝试使用香草javascript来更改svg的href,但是在研究了解决方案之后,遇到了砖墙。

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> 

正如我评论过的:您需要使用svg xlink命名空间: http://www.w3.org/1999/xlink : http://www.w3.org/1999/xlink 当您动态更改xlink:href的值时,这就是您的操作方式: theUse.setAttributeNS(SVG_XLINK, 'xlink:href', '#theId');

这是一个例子:

 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> 

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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