How to get number of rows in <textarea > using JavaScript?

纵饮孤独 提交于 2019-11-26 05:32:03

问题


I have a <textarea> element. Can I use JavaScript to detect that there are (for example) 10 rows of text in it?


回答1:


Well I found a much simplier way to do this, but you'll need to set the line-height of the textarea in the CSS. I tried to read the line height inside the script ta.style.lineHeight but it doesn't seem to return a value.

CSS

#ta { width: 300px; line-height: 20px; }

HTML

<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>

Script

 var taLineHeight = 20; // This should match the line-height in the CSS
 var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
 ta.style.height = taHeight; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
 var numberOfLines = Math.floor(taHeight/taLineHeight);
 alert( "there are " + numberOfLines + " lines in the text area");

Update: Thanks to @Pebbl for working out the bugs, this is the code needed to get the height of the text content (demo)

var calculateContentHeight = function( ta, scanAmount ) {
    var origHeight = ta.style.height,
        height = ta.offsetHeight,
        scrollHeight = ta.scrollHeight,
        overflow = ta.style.overflow;
    /// only bother if the ta is bigger than content
    if ( height >= scrollHeight ) {
        /// check that our browser supports changing dimension
        /// calculations mid-way through a function call...
        ta.style.height = (height + scanAmount) + 'px';
        /// because the scrollbar can cause calculation problems
        ta.style.overflow = 'hidden';
        /// by checking that scrollHeight has updated
        if ( scrollHeight < ta.scrollHeight ) {
            /// now try and scan the ta's height downwards
            /// until scrollHeight becomes larger than height
            while (ta.offsetHeight >= ta.scrollHeight) {
                ta.style.height = (height -= scanAmount)+'px';
            }
            /// be more specific to get the exact height
            while (ta.offsetHeight < ta.scrollHeight) {
                ta.style.height = (height++)+'px';
            }
            /// reset the ta back to it's original height
            ta.style.height = origHeight;
            /// put the overflow back
            ta.style.overflow = overflow;
            return height;
        }
    } else {
        return scrollHeight;
    }
}

var calculateHeight = function() {
    var ta = document.getElementById("ta"),
        style = (window.getComputedStyle) ?
            window.getComputedStyle(ta) : ta.currentStyle,

        // This will get the line-height only if it is set in the css,
        // otherwise it's "normal"
        taLineHeight = parseInt(style.lineHeight, 10),
        // Get the scroll height of the textarea
        taHeight = calculateContentHeight(ta, taLineHeight),
        // calculate the number of lines
        numberOfLines = Math.ceil(taHeight / taLineHeight);

    document.getElementById("lines").innerHTML = "there are " +
        numberOfLines + " lines in the text area";
};

calculateHeight();
if (ta.addEventListener) {
    ta.addEventListener("mouseup", calculateHeight, false);
    ta.addEventListener("keyup", calculateHeight, false);
} else if (ta.attachEvent) { // IE
    ta.attachEvent("onmouseup", calculateHeight);
    ta.attachEvent("onkeyup", calculateHeight);
}



回答2:


Just one js line:

var rows = document.querySelector('textarea').value.split("\n").length;



回答3:


Assuming you know the line-height, the simplest way to do this would be:

function numOfLines(textArea, lineHeight) {
    var h0 = textArea.style.height;
    ta.style.height = 'auto';
    var h1 = textArea.scrollHeight;
    textArea.style.height = h0;
    return Math.ceil(h1 / lineHeight);
}

The trick here is to set the height to auto first. Then when you access scrollHeight the browser will do the layout and return the correct height including any line wraps. Then restore the textarea height to its original value and return the result.




回答4:


You can access the field via Javascript DOM and simply count the number of newline characters.

oArea = document.getElementById('myTextField');
var aNewlines = oArea.value.split("\n");
var iNewlineCount = aNewlines.length();



回答5:


    function countLines(area,maxlength) {
       // var area = document.getElementById("texta")
        // trim trailing return char if exists
        var text = area.value.replace(/\s+$/g, "")
        var split = text.split("\n")
        if (split.length > maxlength) {
            split = split.slice(0, maxlength);
            area.value = split.join('\n');
            alert("You can not enter more than "+maxlength.toString()+" lines");
        }
        return false;
    }

this is a simple and tested one




回答6:


You can get the actual text height from Element.scrollHeight, but to get the correct height, there has to be a scroll, which means you can temporarily set the text box height to 0, until you get the scroll height value then restore back the CSS height.

One you have that, you calculate the number of lines based on the CSS line-height property value (1 line of text contributes to getComputedStyle(ref).lineHeight pixels), something like...

function getTextareaNumberOfLines(textarea) {
    var previous_height = textarea.style.height, lines
    textarea.style.height = 0
    lines = parseInt( textarea.scrollHeight/parseInt(getComputedStyle(textarea).lineHeight) )
    textarea.style.height = previous_height
    return lines
}

Note: your elements must be present in the DOM in order to get the scrollHeight, lineHeight heights etc. If not already present, add them, calculate the values, then remove them from the DOM.



来源:https://stackoverflow.com/questions/1760629/how-to-get-number-of-rows-in-textarea-using-javascript

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