Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. HTMLTextAreaElement

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

HTMLTextAreaElement

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

* Some parts of this feature may have varying levels of support.

HTMLTextAreaElement 接口提供了特殊的属性和方法,用于控制<textarea> 元素的布局和展示。

must be a string

属性

form只读object: 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个<form> 元素的id 属性或者null
type只读string: 返回字符串textarea
valuestring: Returns / Sets the raw value contained in the control.
textLength只读long: Returns the codepoint length of the control'svalue. Same ascalling value.length
defaultValuestring: Returns / Sets the control's default value, which behaves like theNode.textContent property.
placeholderstring: 返回/设置元素placeholder 属性,用于提示用户在组件中应该输入什么。
rowsunsigned long: Returns / Sets the element'srows attribute, indicating the number of visible text lines for the control.
colsunsigned long: Returns / Sets the element'scols attribute, indicating the visible width of the text area.
autofocusboolean: Returns / Sets the element'sautofocus attribute, indicating that the control should have input focus when the page loads
namestring: Returns / Sets the element'sname attribute, containing the name of the control.
disabledboolean: Returns / Sets the element'sdisabled attribute, indicating that the control is not available for interaction.
HTMLTextAreaElement.labels只读NodeList: Returns a list of label elements associated with this select element.
maxLengthlong: Returns / Sets the element'smaxlength attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.
minLengthlong: Returns / Sets the element'sminlength attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.
accessKeystring: Returns / Sets the element'saccesskey attribute.
readOnlyboolean: Returns / Sets the element'sreadonly attribute, indicating that the user cannot modify the value of the control.
requiredboolean: Returns / Sets the element'srequired attribute, indicating that the user must specify a value before submitting the form.
tabIndexlong: Returns / Sets the position of the element in the tabbing navigation order for the current document.
selectionStartunsigned long: Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as ifsetSelectionRange() had been called with this as the first argument, andselectionEnd as the second argument.
selectionEndunsigned long: Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as ifsetSelectionRange() had been called with this as the second argument, andselectionStart as the first argument.
selectionDirectionstring: Returns / Sets the direction in which selection occurred. This is"forward" if selection was performed in the start-to-end direction of the current locale, or"backward" for the opposite direction. This can also be"none" if the direction is unknown."
validity只读ValidityState object: Returns the validity states that this element is in.
willValidate只读boolean: Returns whether the element is a candidate for constraint validation.false if any conditions bar it from constraint validation, including itsreadOnly ordisabled property istrue.
validationMessage只读string: Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate isfalse), or it satisfies its constraints.
autocomplete实验性
autocapitalize实验性string: Returns / Sets the element's capitalization behavior for user input. Valid values are:none,off,characters,words,sentences.
inputMode实验性
wrapstring: Returns / Sets thewrap HTML attribute, indicating how the control wraps text.

The two propertiestabIndex andaccessKey are inherited fromHTMLElement from HTML5 on, but were defined onHTMLTextAreaElement in DOM Level 2 HTML and earlier specifications.

方法

blur()Removes focus from the control; keystrokes will subsequently go nowhere.
focus()Gives focus to the control; keystrokes will subsequently go to this element.
select()Selects the contents of the control.
setRangeText()Replaces a range of text in the element with new text.
setSelectionRange()Selects a range of text in the element (but does not focus it).
checkValidity()Returnsfalse if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelableinvalid event at the control. It returnstrue if the control is not a candidate for constraint validation, or if it satisfies its constraints.
reportValidity()This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelableinvalid event at the element, and returnsfalse; if there are no problems, it returnstrue.
setCustomValidity(DOMstring)Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

The two methodsblur() andfocus() are inherited fromHTMLElement from HTML5 on, but were defined onHTMLTextAreaElement in DOM Level 2 HTML and earlier specifications.

事件

Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface:

input 事件

Fires when thevalue of an<input>,<select>, or<textarea> element has been changed.

示例

Autogrowing textarea example

Make a textarea autogrow while typing:

JavaScript function:

js
function autoGrow(oField) {  if (oField.scrollHeight > oField.clientHeight) {    oField.style.height = oField.scrollHeight + "px";  }}

CSS:

css
textarea.noscrollbars {  overflow: hidden;  width: 300px;  height: 100px;}

HTML:

html
<form>  <fieldset>    <legend>Your comments</legend>    <p><textarea onkeyup="autoGrow(this);"></textarea></p>    <p><input type="submit" value="Send" /></p>  </fieldset></form>

Insert HTML tags example

Insert some HTML tags orsmiles or any custom text in a textarea.JavaScript function:

js
function insertMetachars(sStartTag, sEndTag) {  var bDouble = arguments.length > 1,    oMsgInput = document.myForm.myTxtArea,    nSelStart = oMsgInput.selectionStart,    nSelEnd = oMsgInput.selectionEnd,    sOldText = oMsgInput.value;  oMsgInput.value =    sOldText.substring(0, nSelStart) +    (bDouble      ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag      : sStartTag) +    sOldText.substring(nSelEnd);  oMsgInput.setSelectionRange(    bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart,    (bDouble ? nSelEnd : nSelStart) + sStartTag.length,  );  oMsgInput.focus();}

CSS to decorate the internal span to behave like a link:

css
.intLink {  cursor: pointer;  text-decoration: underline;  color: #0000ff;}

HTML:

html
<form name="myForm">  <p>    [&nbsp;<span                ><strong>Bold</strong></span    >    |    <span                ><em>Italic</em></span    >    |    <span                >URL</span    >    |    <span                >code</span    >    | <span>smile</span> |    etc. etc.&nbsp;]  </p>  <p>    <textarea name="myTxtArea" rows="10" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem. </textarea    >  </p></form>

Maximum length and number of lines example

Create a textarea with a maximum number of characters per line and a maximum number of lines:

First, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. If the limit has not been reached, it will return the key.

js
function checkRows(oField, oKeyEvent) {  var nKey = (      oKeyEvent ||      /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }    ).keyCode,    // put here the maximum number of characters per line:    nCols = 30,    // put here the maximum number of lines:    nRows = 5,    nSelS = oField.selectionStart,    nSelE = oField.selectionEnd,    sVal = oField.value,    nLen = sVal.length,    nBackward = nSelS >= nCols ? nSelS - nCols : 0,    nDeltaForw =      sVal        .substring(nBackward, nSelS)        .search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,    nRowStart = nBackward + nDeltaForw,    aReturns = (      sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)    ).match(/\n/g),    nRowEnd = nSelE + nRowStart + nCols - nSelS,    sRow =      sVal.substring(nRowStart, nSelS) +      sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),    bKeepCols =      nKey === 13 ||      nLen + 1 < nCols ||      /\n/.test(sRow) ||      ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) &&        (sRow.length < nCols ||          (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));  return (    (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) &&    ((nKey > 32 && nKey < 41) || bKeepCols)  );}

In the HTML we just need to hook our function to theonkeypress event and specify that our textarea does not accept pasting:

html
<form>  <p>    Textarea with fixed number of characters per line:<br />    <textarea      cols="50"      rows="10"      onkeypress="return checkRows(this, event);"      onpaste="return false;"></textarea>  </p></form>

规范

Specification
HTML
# htmltextareaelement

浏览器兼容性

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp