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

标签 javascript html forms textarea rows

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

最佳答案

好吧,我找到了一种更简单的方法来执行此操作,但是您需要在 CSS 中设置文本区域的行高。我试图读取脚本 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 解决了错误,这是获取文本内容高度所需的代码 ( 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);
}

关于javascript - 如何使用 JavaScript 获取 &lt;textarea&gt; 中的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1760629/

相关文章:

javascript - 是否可以在 HTML 中的 'onclick' 上运行 .exe 或 .bat 文件

php - 拉维尔 5 : app() helper function

angular - TypeScript -'s Angular Framework Error - "没有将 exportAs 设置为 ngForm 的指令”

javascript - 防止浏览器产生双击事件

javascript - 什么函数返回另一个参数也声明为常量的函数呢?

javascript - 出于某种原因,我的页脚不太适合移动设备

javascript - 如何通过xhrPost()发送csv文件?

html - 如何创建一个黑色背景的 div 以适应 div 的正后方?

javascript - 我使用java Servlet,提交表单并发送JSON格式的数据后无法重定向到另一个页面

css - 无法在退弹平台上将固定形式居中