我想用相同的文本但以 SVG 格式替換常規的 HTML 跨度。
我見過這樣的例子,但似乎只是在例子中手動輸入了定位,即 x=10 和 y=10,但我不確定原因是什么。
使用跨度,我可以將文本垂直居中和水平居中,但對于 SVG,似乎我必須明確告訴它將文本放在父元素中的哪個位置,而默認值不設定 x 或 y 會將文本置于框架之外。
這不一定是壞事,但我不知道如何正確定位它。特別是因為默認定位似乎將文本放在父 SVG 的視圖之上和之外。
我什至在這篇文章中添加了文本錨和主要基線屬性:
如何在 SVG 矩形中放置和居中文本
但這似乎沒有任何作用。
這是我到目前為止所擁有的。
var spantext = jQuery('.mytext').html();
var width = jQuery('.mytext').width();
var height = jQuery('.mytext').height();
var fontsize = jQuery('.mytext').css('font-size');
var color = jQuery('.mytext').css('color');
var newsvg = '<svg style="outline: 1px solid red; font-size: ' fontsize '; overflow: visible; font-color:' color '" width="' width '" height="' height '"><tspan x="0" y="0" width="' width '" height="' width '"><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">' spantext '</text></tspan></text></svg>';
jQuery('.mytext').replaceWith(newsvg);
svg text{
text-anchor: middle;
dominant-baseline: middle;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
HTML SPAN VERSION: <br><br>
<span class="originaltext" style="font-size:15px;color:red;">Text Should Look Like This</span><br><br>
SVG VERSION: (Red Border Added for Clarification)<br><br>
<span class="mytext" style="font-size:15px;color:red;">Text Should Look Like This</span>
uj5u.com熱心網友回復:
像這樣的東西?它在盒子的中央。
我已經用 innerHTML 替換了 jQuery 分配,因為 jQuery 和 SVG 不能真正一起作業。
var spantext = jQuery('.mytext').html();
var width = jQuery('.mytext').width();
var height = jQuery('.mytext').height();
var fontsize = jQuery('.mytext').css('font-size');
var color = jQuery('.mytext').css('color');
var newsvg = '<svg style="outline: 1px solid red; font-size: ' fontsize '; overflow: visible; font-color:' color '" width="' width '" height="' height '"><text dominant-baseline=" ideographic" y="' height '"><tspan>' spantext '</tspan></text></svg>';
document.querySelector('.mytext').innerHTML = newsvg;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
HTML SPAN VERSION: <br><br>
<span class="originaltext" style="font-size:15px;color:red;">Text Should Look Like This</span><br><br>
SVG VERSION: (Red Border Added for Clarification)<br><br>
<span class="mytext" style="font-size:15px;color:red;">Text Should Look Like This</span>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481555.html
