JS/jQuery:尝试通过 substr 在一定宽度内适合任意文本字符串 [英] JS/jQuery: Trying to fit an arbitrary text string within a certain width through substr
问题描述
我正在尝试获取一个文本字符串(例如测试"一词)并计算该字符串在屏幕上显示时是否会超过特定宽度.我通过将它放在一个元素中并使用 width() 来做到这一点.
I'm trying to take a text string, (e.g. the word "testing") and calculating if the string, when displayed on screen, will exceed a certain width. I do this by putting it in a element and using width().
现在,问题是我想一次将文本字符串减少一个字符,然后确定宽度.如果宽度在130px"之内,那么我将返回该截断的字符串.我有以下递归函数,但我对 Js/jQuery 很陌生,不确定我做错了什么.如果确定字符串需要截断,则函数返回 undefined.
Now, the thing is I want to reduce the text string by a character at a time, and then determining the width. If the width is within say "130px", then i'll return that truncated string. I have the following recursive function, but I'm quite new to Js/jQuery and am unsure what I did wrong. If the string is determined to require truncating, the function returns undefined.
非常感谢任何帮助.非常感谢!
Any help is greatly appreciated. Thanks a lot!
function fitWidth(str) {
var width = $('span.width').html(str).width();
if (width > '130') {
strlength = str.length-1;
str = str.substr(0,strlength);
fitWidth(str);
} else {
return str; // something wrong here?
}
}
var testStr = 'Lorem Ipsum';
alert(fitWidth(testStr)); // returns undefined if it was truncated
如果 str 需要截断,fitWidth() 将返回undefined"
if str requires truncating, fitWidth() will return "undefined"
推荐答案
递归情况下需要说return fitWidth(str);
.
这篇关于JS/jQuery:尝试通过 substr 在一定宽度内适合任意文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!