如何查找文本区域中的文本是否换行? [英] How to find whether text in a text area is wrapped to multiple lines?
问题描述
如何查找文本区域中的长文本是否被包裹成两行或更多行?
我不是在讨论此处的新行字符.
我知道插件 Textarea行数
有没有更简单的方法?
我对此进行了实验,并提出了涉及以下内容的黑客:
-
在文本区域中禁用文本换行(加上禁用填充)
-
检查文本区域的
scrollWidth
是否大于其width
.
我使用的基本逻辑是,如果文本跨越多行,这意味着当自动换行关闭时,我们应该得到一个水平滚动条.
演示: http://jsfiddle.net/fnG3d/ >
免责声明:下面的代码是10分钟的拨弄的结果,绝对不是生产质量的结果
function checkMulti(id) {
var ta = $('#'+id), multi = false;
// disable wrapping, padding and enable horiz scoll
ta.addClass('nowrap');
// check if there is anything to be scrolled horizontally (means multi-lines otherwise)
multi = ( ta[0].scrollWidth > ta.width() );
// checking done. remove the class.
ta.removeClass('nowrap');
alert('Spread over multiple-lines: ' + multi);
}
/* the nowrap class */
.nowrap {
overflow-x: scroll;
white-space: nowrap;
padding: 0;
}
How can I find whether a long text in a textarea is wrapped into two or more lines?
I'm not talking about the new line chars as discussed here.
I'm aware of the plugin Textarea Line Count
Any simpler method?
I experimented on this and came up with a hack that involves the following:
Disabling text-wrapping in the textarea (plus disable padding)
Checking if the textarea's
scrollWidth
is greater than it'swidth
.
The basic logic i used was that if the text is spanning multiple lines, that means when wrapping is turned off, we should get a horizontal scrollbar.
Demo: http://jsfiddle.net/fnG3d/
Disclaimer: The code below is the result of a 10 minute fiddle, definitely not production quality
function checkMulti(id) {
var ta = $('#'+id), multi = false;
// disable wrapping, padding and enable horiz scoll
ta.addClass('nowrap');
// check if there is anything to be scrolled horizontally (means multi-lines otherwise)
multi = ( ta[0].scrollWidth > ta.width() );
// checking done. remove the class.
ta.removeClass('nowrap');
alert('Spread over multiple-lines: ' + multi);
}
/* the nowrap class */
.nowrap {
overflow-x: scroll;
white-space: nowrap;
padding: 0;
}
这篇关于如何查找文本区域中的文本是否换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!