Skip to main content
 首页 » 编程设计

jquery之如何拆分输入值并插入到 tspan 中

2026年09月08日2JeffreyZhao

我想分割用户在输入文本框中输入的文本并附加到 svg 文本的 tspan 中

示例:

<input type="text" autofocus/> 

输入的文本例如:“我有一些文本在此容器中换行成三行”

我想让我的 jquery/javascript 解析这些行并将其变成这样:

<text text-anchor="start" y="152"> 
<tspan x="212" dy="-15">I have some text that</tspan> 
<tspan x="212" dy="20">wraps onto three </tspan> 
<tspan x="212" dy="22">lines in this container</tspan> 
</text> 

注意:文本将根据 svg 形状的宽度减去 5px 进行分割,以将文本保留在边框内

到目前为止我尝试过这个:

            var output; 
            window.onchange = onchange; 
            function onchange(e) 
            { 
                output = e.target.value; 
                var width = e.target.value.length; 
                var element = document.getElementById("text"); 
                var height = element.clientHeight; 
                console.log("Width of text:" + width); 
                console.log("Height of text:" + height); 
                console.log("Text entered: " + output); 
 
                var words  = output.split(/[ ,]+/); 
                console.log(words ); 
                e.target.value = ''; 
            } 
 
            var el = document.getElementById("rect"); // or other selector like querySelector() 
            var rect = el.getBoundingClientRect(); // get the bounding rectangle 
 
            console.log("Width of rect: " + rect.width); 
            console.log("Height of rect: " + rect.height); 
 
            $("input[type='text']").bind('keydown', function () { 
                $(this).attr("size", Math.max(5, $(this).val().length)); 
            }); 

请您参考如下方法:

尝试下划线模板,看起来你让这个变得比它需要的更复杂(我也这样做;所以我知道)