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

早过忘川 提交于 2019-12-06 08:33:51

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