如何使用 JavaScript 获取 <textarea > 中的行数?

IT技术 javascript html forms textarea rows
2021-02-05 09:18:52

我有一个<textarea>元素。我可以使用 JavaScript 来检测其中有(例如)10 行文本吗?

6个回答

好吧,我找到了一种更简单的方法来执行此操作,但是您需要在 CSS 中设置 textarea 的行高。我试图读取脚本中的行高,ta.style.lineHeight但它似乎没有返回值。

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>

脚本

 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");

更新:感谢@Pebbl 解决了错误,这是获取文本内容高度所需的代码(演示

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);
}
我有 lineHeight=20 和 textarea height=40,当我添加文本时,calculateContentHeight 返回 21、41、60、80、100。(height++)+'px'需要替换为(++height)+'px'
2021-03-14 09:18:52
+1,这是迄今为止最可靠的方法。一个注意事项:确保 textarea 以 开头rows=1,否则它scrollHeight可能会人为地高。
2021-04-01 09:18:52
@Mottie 不错 :) 如果您有兴趣,我已经将一些自动调整大小的 textarea 逻辑与您的行数相结合,因此现在它应该是全面的 - 对于大多数浏览器 - 即使 ta 大于内容。jsfiddle.net/PfD7L/1
2021-04-06 09:18:52
感谢您的输入@pebbl!我结合了上面的建议并做了一个演示请注意,当您在现代浏览器中手动调整 textarea 大小时,行数将更改以匹配调整后的高度而不是内容。
2021-04-07 09:18:52
@Mottie.style对象只会返回内联样式。要获得计算值,您应该使用window.getComputedStyle并回退到Elm.currentStyle旧 IE。除此之外+1 :)
2021-04-10 09:18:52

只有一行js:

var rows = document.querySelector('textarea').value.split("\n").length;
我遇到了这个问题,具体取决于操作系统。特别是\r、\r\n、\n\r 和\n 之间的区别。我不记得确切的原因,但实际上很难以这种方式彻底地做到这一点。
2021-03-16 09:18:52
@intcreator 然后使用wrap="off"属性
2021-03-30 09:18:52
如果有多行不是因为换行符而是因为一行溢出到下一行怎么办?
2021-04-13 09:18:52

假设您知道行高,最简单的方法是:

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

这里的技巧是将高度设置为auto第一个。然后,当您访问 scrollHeight 时,浏览器将进行布局并返回正确的高度,包括任何换行。然后将textarea的高度恢复到原来的值,返回结果。

您可以从 获取实际文本高度Element.scrollHeight,但要获得正确的高度,必须有一个滚动,这意味着您可以暂时将文本框高度设置为0,直到获得滚动高度值然后恢复 CSS 高度。

你有一个,你计算基于 CSS line-height 属性值的行数(1 行文本对getComputedStyle(ref).lineHeight像素有贡献),比如......

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
}

注意:您的元素必须存在于 DOM 中才能获得 scrollHeight、lineHeight 高度等。如果尚未存在,请添加它们,计算值,然后将它们从 DOM 中删除。

确保line-heightcss 属性是一个数值(即不是normal或类似的字符串)
2021-04-04 09:18:52
    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;
    }

这是一个简单且经过测试的

换行符并不能明确指出换行符。
2021-04-01 09:18:52
当然可以。然而,换行并不能明确表示换行。
2021-04-08 09:18:52