如何获取< textarea>中的行数使用JavaScript? [英] How to get number of rows in <textarea > using JavaScript?

查看:147
本文介绍了如何获取< textarea>中的行数使用JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

更简单的方法来做到这一点,但你需要在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。在faucibus orci luctus et ultrices posuere cubilia Curae中的Vestibulum ante ipsum primis; Cras congue congue purus,quis imperdiet tellus ornare in。Nulla facilisi。 Nulla elementum posuere odio uttricies。 Nullam tempus tincidunt elit eget posuere。 Pellentesque坐在amet tellus sapien。 Praesent sed iaculis turpis。 Nam quis nibh diam,sed mattis orci。 Nullam ornare adipiscing congue。在这种情况下,不要在非法的情况下继续履行。 Mauris varius dui a dolor convallis iaculis。< / textarea> 

脚本

  var taLineHeight = 20; //这应该与CSS 
中的行高一致var taHeight = ta.scrollHeight; //获取textarea
的滚动高度ta.style.height = taHeight; //这一行是可选的,我将它包含在内,以便您可以更轻松地对展开的textarea中的行进行计数
var numberOfLines = Math.floor(taHeight / taLineHeight);
alert(在文本区域有+ numberOfLines +行);






更新:感谢@Pebbl解决错误,这是获取文本内容高度所需的代码( demo ) (b,scanAmount){
var origHeight = ta.style.height,
height = ta.offsetHeight,
scrollHeight = ta.scrollHeight,
overflow = ta.style.overflow;
///如果ta大于内容
,只会打扰if(height> = scrollHeight){
///检查我们的浏览器是否支持更改维度
///计算中途通过函数调用...
ta.style.height =(height + scanAmount)+'px';
///,因为滚动条会导致计算问题
ta.style.overflow ='hidden';
///通过检查scrollHeight更新
if(scrollHeight< ta.scrollHeight){
///现在尝试并向下扫描ta的高度
///直到(ta.offsetHeight> = ta.scrollHeight){
ta.style.height =(height - = scanAmount)+'px'时,scrollHeight大于高度
; (b.offsetHeight< ta.scrollHeight){
ta.style.height =(height ++)+(

///更确切地说得到确切的高度
+ 像素;
}
///将ta重新设置为原始高度
ta.style.height = origHeight;
///把溢出放回
ta.style.overflow = overflow;
返回高度;
}
} else {
return scrollHeight;



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

//只有当它设置在css中时,才会得到行高,
//否则它是正常
taLineHeight = parseInt(style.lineHeight,10),
//获取textarea的滚动高度
taHeight = calculateContentHeight(ta,taLineHeight),
//计算行数
numberOfLines = Math.ceil(taHeight / taLineHeight);

document.getElementById(lines)。innerHTML =在文本区域有+
numberOfLines +行。
};

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


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

解决方案

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

这篇关于如何获取&lt; textarea&gt;中的行数使用JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆