Home  >  Article  >  Web Front-end  >  Complete list of textarea attributes in HTML (set default value, height adaptive, obtain content, limit the number of input characters, placeholder)

Complete list of textarea attributes in HTML (set default value, height adaptive, obtain content, limit the number of input characters, placeholder)

PHP中文网
PHP中文网Original
2017-07-23 15:10:0629937browse


1.textarea settings default value

<span style="font-family: Arial, Helvetica, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); ">
HTML:</span><form action="test" name="myForm" onsubmit="set()">
<textarea rows="0" cols="0" name="jsonHidden" readonly="readonly" style="display:none;"></textarea>
<input type="submit" value="提交" >

This code sets a textarea text box and sets it to hidden

2.textarea is highly adaptive

Today we need a page for replying to comments. The initial interface given by the designer is a box with only one line. Then I was thinking about how to implement this interaction better, and then I remembered what Sina Weibo did: click on a comment, and one line will be displayed by default. When the input text exceeds one line or Enter is entered, the height of the input box will change accordingly until the input complete. I immediately felt that this detail was done quite well and I could imitate it. Below are two ways to achieve high adaptability of textarea. One is to use div to simulate textarea, and use CSS to control the style without js; the other is to use JS to control (because of browser compatibility issues, so write It’s more troublesome to get up);

Method 1: div simulates textarea text area to easily achieve height adaptation

Complete list of textarea attributes in HTML (set default value, height adaptive, obtain content, limit the number of input characters, placeholder)

Because textarea does not support adaptive height, just set the height Or after the number of rows, scroll bars will be displayed in the excess part, which looks unsightly.

When using DIV to simulate, the first problem encountered is: how to implement the input function of div?

Maybe this is the first time we have seen this attribute contenteditable. For example, adding contenteditable="true" to an ordinary block element will enable editing and the cursor will appear. For example,

<div contenteditable="true"></div>

Although the contenteditable attribute is the content in HTML5, IE seems to have supported this tag attribute for a long time. Therefore, there is no need to worry too much about compatibility.

CSS code

.textarea{
    width:400px;
    min-height:20px;
    max-height:300px;
    _height:120px;
    margin-left:auto;
    margin-right:auto;
    padding:3px;
    outline:0;
    border:1pxsolid#a0b3d6;
    font-size:12px;
    line-height:24px;
    padding:2px;
    word-wrap:break-word;
    overflow-x:hidden;
    overflow-y:auto;
 
    border-color:rgba(82,168,236,0.8);
    box-shadow:inset01px3pxrgba(0,0,0,0.1),008pxrgba(82,168,236,0.6);
}

Method 2: Text box textarea adapts height according to input content

Demo demo address: http://www.xuanfengge.com/demo/201308 /textarea/demo2.html

This writing method is written in native JS, taking into account many compatibility issues, and has the same function as Sina Weibo’s reply effect. Interested children can analyze the code carefully.

CSS code

#textarea
 { 
    display:block;
    margin:0auto;
    overflow:hidden;
    width:550px;
    font-size:14px;
    height:18px;
    line-height:24px;
    padding:2px;
}
textarea{
    outline:0none;
    border-color:rgba(82,168,236,0.8);
    box-shadow:inset01px3pxrgba(0,0,0,0.1),008pxrgba(82,168,236,0.6);
}

JS code

/**
 * 文本框根据输入内容自适应高度
 * @param                {HTMLElement}        输入框元素
 * @param                {Number}                设置光标与输入框保持的距离(默认0)
 * @param                {Number}                设置最大高度(可选)
 */
var autoTextarea = function (elem, extra, maxHeight) {
        extra = extra || 0;
        var isFirefox = !!document.getBoxObjectFor || &#39;mozInnerScreenX&#39; in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf(&#39;Opera&#39;),
                addEvent = function (type, callback) {
                        elem.addEventListener ?
                                elem.addEventListener(type, callback, false) :
                                elem.attachEvent(&#39;on&#39; + type, callback);
                },
                getStyle = elem.currentStyle ? function (name) {
                        var val = elem.currentStyle[name];
 
                        if (name === &#39;height&#39; && val.search(/px/i) !== 1) {
                                var rect = elem.getBoundingClientRect();
                                return rect.bottom - rect.top -
                                        parseFloat(getStyle(&#39;paddingTop&#39;)) -
                                        parseFloat(getStyle(&#39;paddingBottom&#39;)) + &#39;px&#39;;        
                        };
 
                        return val;
                } : function (name) {
                                return getComputedStyle(elem, null)[name];
                },
                minHeight = parseFloat(getStyle(&#39;height&#39;));
 
        elem.style.resize = &#39;none&#39;;
 
        var change = function () {
                var scrollTop, height,
                        padding = 0,
                        style = elem.style;
 
                if (elem._length === elem.value.length) return;
                elem._length = elem.value.length;
 
                if (!isFirefox && !isOpera) {
                        padding = parseInt(getStyle(&#39;paddingTop&#39;)) + parseInt(getStyle(&#39;paddingBottom&#39;));
                };
                scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
 
                elem.style.height = minHeight + &#39;px&#39;;
                if (elem.scrollHeight > minHeight) {
                        if (maxHeight && elem.scrollHeight > maxHeight) {
                                height = maxHeight - padding;
                                style.overflowY = &#39;auto&#39;;
                        } else {
                                height = elem.scrollHeight - padding;
                                style.overflowY = &#39;hidden&#39;;
                        };
                        style.height = height + extra + &#39;px&#39;;
                        scrollTop += parseInt(style.height) - elem.currHeight;
                        document.body.scrollTop = scrollTop;
                        document.documentElement.scrollTop = scrollTop;
                        elem.currHeight = parseInt(style.height);
                };
        };
 
        addEvent(&#39;propertychange&#39;, change);
        addEvent(&#39;input&#39;, change);
        addEvent(&#39;focus&#39;, change);
        change();
};

HTML code (written in the body)

<textareaid="textarea"placeholder="回复内容"></textarea>
    <script>
        vartext=document.getElementById("textarea");
        autoTextarea(text);//
 调用
    </script>

3.textarea gets content

Method 1: JS can use document.getElementById(v).value to obtain the content in the textarea.

For example:


<textarea id="abc" name="t" cols="72" rows="12">123456</textarea>
<script>
var x=document.getElementById("abc").value;/这个x的值就是获取到的内容
alert(x);
</script>

Method 2:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<textarea id=&#39;myText&#39;>这里是textarea内容</textarea>
<script type="text/javascript" src="Js/jquery-1.7.js"></script>
<script type="text/javascript">
alert("JS获取方式:"+document.getElementById("myText").value);//JS
alert("JQuery获取方式:"+$("#myText").val());//Jquery
</script>
</body>
</html>


##4.textarea restriction Number of input words

Realize textarea to limit the number of input words (including Chinese, only 10 can be input, full ASCII code can input 20)

textarea is called text area, also known as text area, that is Multi-line text input controls with scroll bars are often used in web page submission forms. Unlike the single-line text box text control, it cannot limit the number of words through the maxlength attribute. For this reason, other methods must be found to limit it to meet the preset requirements.

The usual approach is to use #scripting language to limit the number of words entered in the textarea text field, which is simple and practical. Suppose we have a textarea text area with an ID of txta1. We can limit its keyboard input characters to 10 characters (Chinese characters or other small-angle characters) through the following code:

<script language="#" type="text/ecmascript"> 
window.onload = function() 
{ 
document.getElementById(&#39;txta1&#39;).onkeydown = function() 
{    
    if(this.value.length >= 10) 
      event.returnValue = false; 
} 
} 
</script>

The principle is to pass keydown ( (Keyboard key pressed) event monitors the text area with the specified ID number. As you can imagine, it can only limit keyboard input. If the user pastes text in the clipboard through the right mouse button, it cannot control the number of words.


Input via keyboard, only 10 characters can be entered in the above text area. However, our goal was not achieved! Just copy some text and try pasting it with the right mouse button and see what happens.


You can find other JS scripts similar to the above on the Internet. No matter how excellent they are, their principles are the same. They monitor keyboard key operation events such as keydown, keyup or keypress. Input in the text area cannot prevent the right mouse button from being pasted. For this reason, if we must really limit the number of words in the textarea, we have to add another lock to the web page - disabling the right mouse button. This will undoubtedly cost extra. At the same time, It may also be something that the web page creator is not necessarily willing to do. In fact, there is a simpler way, using the onpropertychange attribute.

onpropertychange可以用来判断预定元素的value值,当元素的value值发生变化时判断事件就会被触发,仅关心被监测元素的value值,避开了输入的来源,从而可以比较理想地达成我们的限制字数这一目的。它属于JS范畴,可以在表单方框区代表中嵌套使用,以下是代码和效果样式,可以像上面那样测试输入,你会发现它真正达到目的:不管用什么方式输入,它只能输入100个字(汉字或其他小解符号):

代码:

<textarea onpropertychange="if(value.length>100) value=value.substr(0,100)" class="smallArea" cols="60" name="txta" rows="8"></textarea>

当然,为了更为保险,处理表单数据的后台脚本程序还应该对提交来的数据进行再一次的检测,如果字数超出预设的数量则进行相应处理,这样才达到真正限制字数的目的。(完)

另外一种方法实现textarea限制输入字数(包含中文只能输入10个,全ASCII码能够输入20个)

<script> 
function check() { 
var regC = /[^ -~]+/g; 
var regE = /\D+/g; 
var str = t1.value; 
if (regC.test(str)){ 
    t1.value = t1.value.substr(0,10); 
} 
if(regE.test(str)){ 
    t1.value = t1.value.substr(0,20); 
} 
} 
</script> 
<textarea maxlength="10" id="t1" onkeyup="check();"> 
</textarea>

 还有一种方式:

function textCounter(field, maxlimit) { 
if (field.value.length > maxlimit){ 
field.value = field.value.substring(0, maxlimit); 
}else{ 
document.upbook.remLen.value = maxlimit - field.value.length; 
} 
}
<textarea name=words cols=19 rows=5 class=input1 onPropertyChange= "textCounter(upbook.words, 50) "> textarea> 剩余字数: <input name=remLen type=text id= "remLen " style= "background-color: #D4D0C8; border: 0; color: red " value=50 size=3 maxlength=3 readonly>
 
 
function LimitTextArea(field){  
   maxlimit=200;    
    if (field.value.length > maxlimit)     
     field.value = field.value.substring(0, maxlimit);           
}
<textarea cols=50 rows=10 name="comment" id="commentarea" onKeyDown="LimitTextArea(this)" onKeyUp="LimitTextArea(this)" onkeypress="LimitTextArea(this)" >
</textarea>

 

title="The textarea width must less than 300 characters." 放在textarea 里面提示输入最大字节数。

例如:

<textarea title="The textarea width must less than 300 characters." cols=50 rows=10 name="comment" id="commentarea" onKeyDown="LimitTextArea(this)" onKeyUp="LimitTextArea(this)" onkeypress="LimitTextArea(this)" ></textarea>

5.textarea 换行

最近碰到一个数据转来转去转到Textrea里面是否能真正按行存放的问题,在这里总结一下:

问题描述:

比如get数据到一个TextArea里面,如“AAA BBB”,想把这段文字在TextArea里面真正按行存放,而不是显示出来按行存放(所谓的真正按行存放就是,再把这个TextArea的数据post到另外一个页面的Textarea里面仍是按行存放)

问题解决1:

一开始是提交数据的时候格式是AAA
BBB,但是这是显示换行,其实在TextArea里面并不是真正按行存放的,因为这个时候再提交给另外一个TextArea的时候就是显示AAABBB,而不是换行显示了,因此仅仅是显示按行存放而已

问题基础知识:

HTML里面的换行是
,而TextArea的换行是/n

问题解决2:

先提交数据再使用Javascript对
和/n进行替换

提交的时候仍是
作为分隔符

然后提交完毕以后

 <script>
         //换行转回车
         var haha=document.getElementById("SendTextArea").value;
         haha=haha.replace(&#39;<br />&#39;,&#39;/n&#39;);
         document.getElementById("SendTextArea").value=haha;
 </script>

6.textarea固定大小

TML 标签 textarea 在大部分浏览器中只要指定行(rows)和列(cols)属性,就可以规定 textarea 的尺寸,大小就不会改变,不过更好的办法是使用 CSS 的 height 和 width 属性,但是Chrome,Safari和FireFox渲染的效果不同,可以拖动右下角图标改变大小。但是过分拖动大小会影响页面布局,使页面变得不美观。可以通过添加如下两个样式禁用拖动,固定大小:

1:彻底禁用拖动(推荐)

resize: none;

2:只是固定大小,右下角的拖动图标仍在

width: 200px;    
height: 100px;    
max-width: 200px;    
max-height: 100px;

3:浏览器信息:

Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.218 Safari/535.1

7.textarea value

最近在做一个小项目,才发现原来textarea中居然没有value属性。

<tr>    
  <th>姓名*</th>       
  <td><span><input type="text" class="TextBox" id="xm" name="xm" /></span></td>
</tr>
<!--平时用<input>标签比较多,一般在其内添加个value属性就可以获取到值,但是在<textarea>标签中添加该属性却获取不到相应的值,具体解决的办法是用以下的格式即可:-->
<textarea>(在这里添加内容)</textarea>

8.textarea placeholder

placeholder 属性适用于以下的 类型:text, search, url, telephone, email 以及 password。
这个属性是html5才有的新属性,原来的HTML 4.01 与 HTML 5 之间的差异。

The above is the detailed content of Complete list of textarea attributes in HTML (set default value, height adaptive, obtain content, limit the number of input characters, placeholder). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn