How to find whether text in a text area is wrapped to multiple lines?

混江龙づ霸主 提交于 2019-12-07 21:53:26

问题


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?


回答1:


I experimented on this and came up with a hack that involves the following:

  1. Disabling text-wrapping in the textarea (plus disable padding)

  2. Checking if the textarea's scrollWidth is greater than it's width.

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;
}


来源:https://stackoverflow.com/questions/15835327/how-to-find-whether-text-in-a-text-area-is-wrapped-to-multiple-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!