这里的这一章有一个使用 javascript 而没有 JQuery 的解决方案:http: //blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/
在 jsfiddle 中完成:http: //jsfiddle.net/ZfDYG/
编辑 - 只需阅读大约 2 行文本:http: //jsfiddle.net/ZfDYG/8/
代码(为了完整性):
String.prototype.visualLength = function() {
var ruler = $("ruler");
ruler.innerHTML = this;
return ruler.offsetWidth;
}
function $(id) {
return document.getElementById(id);
}
var s = "Some text that is quite long and probably too long to fit in the box";
var len = s.visualLength();
String.prototype.trimToPx = function(length,postfix) {
postfix = postfix || '';
var tmp = this;
var trimmed = this;
if (tmp.visualLength() > length) {
trimmed += postfix;
while (trimmed.visualLength() > length) {
tmp = tmp.substring(0, tmp.length-1);
trimmed = tmp + postfix;
}
}
return trimmed;
}
String.prototype.wrapToLength = function(complete) {
if(complete[this.length] == ' ' || complete[this.length - 1] == ' ') return;
var wrapped = this;
var found = false;
for(var i = this.length-1; i > 0 && !found; i--) {
if(this[i] == ' ') {
wrapped = this.substring(0, i);
found = true;
}
}
return wrapped;
}
var firstLine = s.trimToPx(240).wrapToLength(s);
var secondLine = s.substring(firstLine.length, s.length);
$('output').innerHTML= firstLine+' '+secondLine.trimToPx(240,'...');
html:
<span id="ruler"></span>
<div id="output"></div>
CSS:
#ruler { visibility: hidden; white-space: nowrap; }
#output {
width: 240px;
height: 50px;
border: 1px solid red;
}
如果这在您的盒子上仍然太慢,我想应该可以通过从更大的添加开始以向最终长度(有点像弹簧)振荡而不是慢慢增加来加速while循环。