考虑以下 SVG 块:
<defs>
<radialGradient id="gradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:#568f82;stop-opacity:1" />
<stop offset="100%" style="stop-color:#568f82;stop-opacity:0" />
</radialGradient>
</defs>
创建这些元素的相应 JavaScript 是:
var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
var radialGradient = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
radialGradient.id = 'gradient';
radialGradient.setAttribute('cx', '50%');
radialGradient.setAttribute('cy', '50%');
radialGradient.setAttribute('fx', '50%');
radialGradient.setAttribute('fy', '50%');
radialGradient.setAttribute('r', '50%');
var stop1 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
stop1.setAttribute('offset', '0%');
stop1.setAttribute('style', 'stop-color:#568f82;stop-opacity:1');
radialGradient.appendChild(stop1);
var stop2 = document.createElementNS('http://www.w3.org/2000/svg', 'path');
stop2.setAttribute('offset', '100%');
stop2.setAttribute('style', 'stop-color:#568f82;stop-opacity:0');
radialGradient.appendChild(stop2);
defs.appendChild(radialGradient);
this.svgElement.appendChild(defs);
有没有办法在 JavaScript 中使用内联 XML 标记?我尝试了类似以下的方法,但没有任何运气:
var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
defs.innerHTML =
'<radialGradient id="gradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">' +
' <stop offset="0%" style="stop-color:#568f82;stop-opacity:1" />' +
' <stop offset="100%" style="stop-color:#568f82;stop-opacity:0" />' +
'</radialGradient>';
似乎这innerHTML
不是 的属性SVGElement
。