我找到了一个解决我的问题的 hack 解决方案,它基于通过将文本克隆到“内联块”跨度并测量该文本宽度来测量一行文本的宽度。结果如下:
http://jsfiddle.net/RPgrq/
var ta = document.getElementsByTagName('textarea')[0],
sp = document.getElementById('span'),
false_keys = [37,38, 39, 40] , width= 150;
ta.addEventListener('keyup', function(e) {
var text = this.value, count = text.length, n = 0, test_width, new_string = '', caret_start = this.selectionStart, caret_end = this.selectionEnd;
if(false_keys.indexOf(e.keyCode) > -1) { return; }
sp.innerHTML = '';
for(n = 0; n < count ; n++) {
switch(text[n]) {
case ' ' : sp.innerHTML += ' '; break;
case '\n': sp.innerHTML = ''; break;
default: sp.innerHTML += text[n]; break;
}
new_string += text[n];
test_width = parseInt(window.getComputedStyle(sp).getPropertyValue('width').slice(0,-2), 10);
if(test_width >= width) {
if(new_string.slice(-1) == ' ' || new_string.slice(-1) == '\n') {
new_string = new_string.slice(0, -1) + '\n';
}
else {
new_string = new_string.replace(/\s([^\s]*)$/, '\n$1');
}
sp.innerHTML = '' ;
}
}
this.value = new_string;
this.setSelectionRange(caret_start, caret_end);
});
(注意:在脚本框架中,您可以设置“宽度”变量来换行)