2016-11-24 158 views
0

是否可以更改SVG <text>元素的單個字符的顏色?例如,在以下示例文本中,我希望字符5爲綠色,字符6爲紅色。更改SVG文本元素中單個字符的顏色

word = "{5,6}" 
tspan.document.createElementNS(namespace,"tspan"); 
tspan.textContent = word; 

//tspan.setAttributeNS(null,"fill","green"); 
textNode.appendChild(tspan); 

回答

1

您可以使用setAttribute代替setAttributeNS設置顏色。

例如:

<script> 
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 
    svg.setAttribute('style', 'border: 0px solid black'); 
    svg.setAttribute('width', '600'); 
    svg.setAttribute('height', '250'); 

    //Text 
    var newText = document.createElementNS("http://www.w3.org/2000/svg","text"); 
    newText.setAttributeNS(null,"x",20);  
    newText.setAttributeNS(null,"y",100); 
    newText.setAttribute('style', 'font-size:24px'); 

    //Text span 
    var txtSpan1 = document.createElementNS("http://www.w3.org/2000/svg","tspan"); 
    txtSpan1.textContent = "Eins"; 
    newText.appendChild(txtSpan1); 

    //Text span with color 
    var txtSpan2 = document.createElementNS("http://www.w3.org/2000/svg","tspan"); 
    txtSpan2.textContent = "t"; 
    txtSpan2.setAttribute('style', 'fill:green'); 
    newText.appendChild(txtSpan2); 

    //Text span without color 
    var txtSpan3 = document.createElementNS("http://www.w3.org/2000/svg","tspan"); 
    txtSpan3.textContent = "e"; 
    newText.appendChild(txtSpan3); 
    var txtSpan4 = document.createElementNS("http://www.w3.org/2000/svg","tspan"); 

    svg.appendChild(newText); 
    document.body.appendChild(svg); 

</script> 

jsFiddle爲另一種方式做到使用文本元素的innerHTML屬性中的文本着色。