当我尝试使用下面的代码并动态传递值来渲染栏时,它不会显示带颜色的 svg: 以下是参考代码
<template>
<label>
<strong>Test Bar1</strong>
</label>
<svg height="24" width="400" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grayGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#f5f5f5" />
<stop offset="100%" stop-color="#e5e5e5" />
</linearGradient>
<linearGradient id="greenGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#4dcb00" />
<stop offset="100%" stop-color="#286900" />
</linearGradient>
</defs>
<rect fill="url(#grayGradient)" x="0" y="0" width="100%" height="100%" rx="12" ry="12" />
<rect id="greenId" fill="url(#greenGradient)" x="0" y="0" width="0%" height="100%" rx="12" ry="12" />
</svg>
<label>
<strong>Test 2 Bar</strong>
</label>
<svg height="24" width="400" xmlns="http://www.w3.org/2000/svg">
<rect fill="url(#grayGradient)" x="0" y="0" width="100%" height="100%" rx="12" ry="12" />
<rect id="greenId1" fill="url(#greenGradient)" x="0" y="0" width="0%" height="100%" rx="12" ry="12" />
</svg>
</template>
就像评论的那样,你不能有重复的 id 值。
将 defs 元素移出到自己的 SVG 中。 SVG 应该被隐藏(这里我将宽度和高度设置为
0
)。从模板中的 rect 元素中删除 id 值。
const menu = document.getElementById('bars');
const temp1 = document.getElementById('temp1');
addbar('Test bar 1');
addbar('Test bar 2');
function addbar(label){
let clone = temp1.content.cloneNode(true);
clone.querySelector('label strong').textContent = label;
menu.appendChild(clone);
}
div#bars {
display: flex;
flex-direction: column;
}
<div id="bars">
</div>
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grayGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#f5f5f5" />
<stop offset="100%" stop-color="#e5e5e5" />
</linearGradient>
<linearGradient id="greenGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#4dcb00" />
<stop offset="100%" stop-color="#286900" />
</linearGradient>
</defs>
</svg>
<template id="temp1">
<label>
<strong>Title</strong>
</label>
<svg height="24" width="400" xmlns="http://www.w3.org/2000/svg">
<rect fill="url(#grayGradient)" x="0" y="0" width="100%" height="100%" rx="12" ry="12" />
<rect fill="url(#greenGradient)" x="0" y="0" width="50%" height="100%" rx="12" ry="12" />
</svg>
</template>