svg中text換行,vml裡面textbox實現換行
阿新 • • 發佈:2019-02-11
svg中text換行:
可以在text中加入tspan元素
例如:
顯示:
<text id="_Gef_14" x="65px" y="28.75px" text-anchor="middle"> <tspan x="81" y="28.75px" dy="-13">啊啊啊啊啊啊啊 </tspan> <tspan x="81" y="28.75px" dy="1">啊啊啊啊啊啊啊 </tspan> <tspan x="81" y="28.75px" dy="15">啊啊啊啊啊啊啊 </tspan> </text>
var _ = this.getTextPosition(this.w, this.h), A = document.createElementNS(Gef.svgns, "text"); A.setAttribute("id", Gef.id()); A.setAttribute("x", _.x); A.setAttribute("y", _.y); A.setAttribute("text-anchor", "middle"); //TODO:修改顯示節點文字換行<text中加入tspan> var MAXIMUM_CHARS_PER_LINE = 7; var LINE_HEIGHT = 14; if(Gef.notEmpty(this.name)){ var sName = this.insertEnter(this.name); var line = ""; if(sName instanceof Array){ _.dy = -13; var words = sName.splice(0,3); if(words.length>=3){ _.dy = -13; if(words[words.length-1]==""){ _.dy = -2; } }else{ _.dy = -2; } for (var n = 0; n < words.length; n++) { var testLine = line + words[n] + " "; if (testLine.length > MAXIMUM_CHARS_PER_LINE) { line = words[n] + " "; // Add a new <tspan> element var svgTSpan = document.createElementNS(Gef.svgns,'tspan'); svgTSpan.setAttribute("x", parseInt(_.x)+16); svgTSpan.setAttribute("y", _.y); svgTSpan.setAttribute("dy",_.dy); var tSpanTextNode = document.createTextNode(line); svgTSpan.appendChild(tSpanTextNode); A.appendChild(svgTSpan); _.dy+=LINE_HEIGHT; } else { line = testLine; } } }else{ _.dy = 0; A.textContent = this.name; } }else{ A.textContent = this.name; } // A.textContent = this.name; $.appendChild(A); this.textEl = A
拆分字串的方法:
insertEnter:function (str){
//分割字串7個一個數組
var s=str,reg=/.{7}/g,rs=s.match(reg);
if(str.length<6){
return str;
}else{
rs.push(s.substring(rs.join('').length));
}
return rs;
}
vml中textbox實現換行效果:
可以通過css樣式控制顯示為換行,加inset屬性,因為內層樣式會限制高度,margin-top等屬性
//節點名字 this.rectEl = B; var _ = this.getTextPosition(this.w, this.h), A = document.createElement("v:textbox"); A.style.textAlign = "center"; A.style.fontFamily = "Verdana"; A.style.fontSize = "12px"; A.style.wordBreak = "break-all"; A.style.wordWrap = "break-word"; A.inset="22pt,0pt,3pt,-60pt";//左上右下 // A.style.whiteSpace = "nowrap"; // A.style.width = "80px"; //word-break:break-all;word-wrap:break-word; A.style.lineHeight = "12px"; A.setAttribute("id", Gef.id()); A.innerHTML = this.name; B.appendChild(A); this.textEl = A
圖:
樣式調整為: