HTMLTextAreaElement
interface provides special properties and methods for manipulating the layout and presentation of
<textarea>
元素。
<div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveAspectRatio="xMinYMin meet"><a xlink:href="../API/EventTarget.html" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="151" y2="25" stroke="#D4DDE4"/><a xlink:href="../API/Node" target="_top"><rect x="151" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a><polyline points="226,25 236,20 236,30 226,25" stroke="#D4DDE4" fill="none"/><line x1="236" y1="25" x2="266" y2="25" stroke="#D4DDE4"/><a xlink:href="../API/Element" target="_top"><rect x="266" y="1" width="75" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="303.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Element</text></a><polyline points="341,25 351,20 351,30 341,25" stroke="#D4DDE4" fill="none"/><line x1="351" y1="25" x2="381" y2="25" stroke="#D4DDE4"/><a xlink:href="../API/HTMLElement" target="_top"><rect x="381" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="436" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLElement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#D4DDE4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#D4DDE4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#D4DDE4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#D4DDE4"/><a xlink:href="../API/HTMLTextAreaElement" target="_top"><rect x="301" y="65" width="190" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="396" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLTextAreaElement</text></a></svg></div>
a:hover text { fill: #0095DD; pointer-events: all;}
accessKey
|
string
:
Returns / Sets the element's
accesskey
属性。
|
autocapitalize
|
string
:
Returns / Sets the element's capitalization behavior for user input. Valid values are:
none
,
off
,
characters
,
words
,
sentences
.
|
autocomplete
|
|
autofocus
|
boolean
:
Returns / Sets the element's
autofocus
attribute, indicating that the control should have input focus when the page loads
|
cols
|
unsigned long
:
Returns / Sets the element's
cols
attribute, indicating the visible width of the text area.
|
defaultValue
|
string
:
Returns / Sets the control's default value, which behaves like the
Node.textContent
特性。
|
被禁用
|
boolean
:
Returns / Sets the element's
被禁用
attribute, indicating that the control is not available for interaction.
|
form
只读
|
object
:
Returns a reference to the parent form element. If this element is not contained in a form element, it can be the
id
attribute of any
<form>
element in the same document or the value
null
.
|
inputMode
|
|
maxLength
|
long
:
Returns / Sets the element's
maxlength
attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.
|
minLength
|
long
:
Returns / Sets the element's
minlength
attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.
|
名称
|
string
:
Returns / Sets the element's
名称
attribute, containing the name of the control.
|
placeholder
|
string
:
Returns / Sets the element's
placeholder
attribute, containing a hint to the user about what to enter in the control.
|
readOnly
|
boolean
:
Returns / Sets the element's
readonly
attribute, indicating that the user cannot modify the value of the control.
|
required
|
boolean
:
Returns / Sets the element's
required
attribute, indicating that the user must specify a value before submitting the form.
|
rows
|
unsigned long
:
Returns / Sets the element's
rows
attribute, indicating the number of visible text lines for the control.
|
selectionDirection
|
string
:
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.
|
selectionEnd
|
unsigned 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 if
setSelectionRange()
had been called with this as the second argument, and
selectionStart
as the first argument.
|
selectionStart
|
unsigned 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 if
setSelectionRange()
had been called with this as the first argument, and
selectionEnd
as the second argument.
|
tabIndex
|
long
:
Returns / Sets the position of the element in the tabbing navigation order for the current document.
|
textLength
只读
|
long
:
Returns the codepoint length of the control's
value
. Same as reading
value.length
|
type
只读
|
string
:
返回字符串
textarea
.
|
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
is
false
), or it satisfies its constraints.
|
validity
只读
|
Returns the validity states that this element is in.
|
value
|
string
:
Returns / Sets the raw value contained in the control.
|
willValidate
只读
|
boolean
:
Returns whether the element is a candidate for constraint validation.
false
if any conditions bar it from constraint validation, including its
readOnly
or
被禁用
特性为
true
.
|
wrap
|
string
:
Returns / Sets the
wrap
HTML attribute, indicating how the control wraps text.
|
HTMLTextAreaElement.labels
只读
|
NodeList
: Returns a list of label elements associated with this element.
|
The two properties
tabIndex
and
accessKey
are inherited from
HTMLElement
from HTML5 on, but were defined on
HTMLTextAreaElement
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()
|
返回
false
if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable
无效
event at the control. It returns
true
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 cancelable
无效
event at the element, and returns
false
; if there are no problems, it returns
true
.
|
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 methods
blur()
and
focus()
are inherited from
HTMLElement
from HTML5 on, but were defined on
HTMLTextAreaElement
in DOM Level 2 HTML and earlier specifications.
监听这些事件使用
addEventListener()
或通过把事件监听器赋值给
on
eventname
property of this interface:
input
event
value
of an
<input>
,
<select>
,或
<textarea>
元素已改变。
Make a textarea autogrow while typing:
function autoGrow (oField) {
if (oField.scrollHeight > oField.clientHeight) {
oField.style.height = oField.scrollHeight + "px";
}
}
textarea.noscrollbars {
overflow: hidden;
width: 300px;
height: 100px;
}
<form>
<fieldset>
<legend>Your comments</legend>
<p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p>
<p><input type="submit" value="Send" /></p>
</fieldset>
</form>
Insert some HTML tags or smiles or any custom text in a textarea.
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:
.intLink {
cursor: pointer;
text-decoration: underline;
color: #0000ff;
}
HTML:
<form name="myForm">
<p>[ <span class="intLink" onclick="insertMetachars('<strong>','<\/strong>');"><strong>Bold</strong></span> | <span class="intLink" onclick="insertMetachars('<em>','<\/em>');"><em>Italic</em></span> | <span class="intLink" onclick="var newURL=prompt('Enter the full URL for the link');if(newURL){insertMetachars('<a href=\u0022'+newURL+'\u0022>','<\/a>');}else{document.myForm.myTxtArea.focus();}">URL</span> | <span class="intLink" onclick="insertMetachars('\n<code>\n','\n<\/code>\n');">code</span> | <span class="intLink" onclick="insertMetachars(' :-)');">smile</span> | etc. etc. ]</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>
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.
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 the `onkeypress` event and specify that our textarea does not accept pasting:
<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>
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'HTMLTextAreaElement' in that specification. |
实时标准 | |
|
HTML5
The definition of 'HTMLTextAreaElement' in that specification. |
推荐 |
属性
tabindex
and
accesskey
, as well as the methods
blur()
and
focus()
are now defined on
HTMLElement
.
The following attributes have been added:
autofocus
,
placeholder
,
dirName
,
wrap
,
maxLength
,
required
,
textLength
,
labels
,
selectionStart
,
selectionEnd
,
selectionDirection
,
validity
,
validationMessage
,和
willValidate
.
The following methods have been added:
checkValidity()
,
setCustomValidity()
,和
setSelectionRange()
.
|
|
DOM (文档对象模型) 2 级 HTML 规范
The definition of 'HTMLTextAreaElement' in that specification. |
过时 |
The property
defaultValue
doesn't contain the initial value of the
value
attribute, but the initial value of the content of the
<textarea>
.
|
|
DOM (文档对象模型) 1 级规范
The definition of 'HTMLTextAreaElement' in that specification. |
过时 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
HTMLTextAreaElement
|
Chrome 1 | Edge 12 | Firefox 1 | IE 8 | Opera 8 | Safari 3 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
autocapitalize
|
Chrome 43 | Edge 79 | Firefox ? | IE ? | Opera ? | Safari ? | WebView Android No | Chrome Android 43 | Firefox Android ? | Opera Android ? | Safari iOS ? | Samsung Internet Android 4.0 |
autocomplete
|
Chrome 66 | Edge ≤79 | Firefox Yes | IE ? | Opera Yes | Safari Yes | WebView Android 66 | Chrome Android 66 | Firefox Android Yes | Opera Android Yes | Safari iOS Yes | Samsung Internet Android 9.0 |
labels
|
Chrome 14 | Edge 18 | Firefox 56 | IE No | Opera Yes | Safari Yes | WebView Android Yes | Chrome Android Yes | Firefox Android 56 | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
reportValidity
|
Chrome 40 | Edge 17 | Firefox 49 | IE No | Opera 27 | Safari 10 | WebView Android 40 | Chrome Android 40 | Firefox Android 64 | Opera Android 27 | Safari iOS 10 | Samsung Internet Android 4.0 |
textLength
|
Chrome 47 | Edge 17 | Firefox 28 | IE No | Opera 30 | Safari 9 | WebView Android Yes | Chrome Android Yes | Firefox Android Yes | Opera Android Yes | Safari iOS Yes | Samsung Internet Android Yes |
完整支持
不支持
兼容性未知
HTMLTextAreaElement
BeforeUnloadEvent
DOMStringMap
ErrorEvent
GlobalEventHandlers
HTMLAnchorElement
HTMLAreaElement
HTMLAudioElement
HTMLBRElement
HTMLBaseElement
HTMLBaseFontElement
HTMLBodyElement
HTMLButtonElement
HTMLCanvasElement
HTMLContentElement
HTMLDListElement
HTMLDataElement
HTMLDataListElement
HTMLDialogElement
HTMLDivElement
HTMLDocument
HTMLElement
HTMLEmbedElement
HTMLFieldSetElement
HTMLFormControlsCollection
HTMLFormElement
HTMLFrameSetElement
HTMLHRElement
HTMLHeadElement
HTMLHeadingElement
HTMLHtmlElement
HTMLIFrameElement
HTMLImageElement
HTMLInputElement
HTMLIsIndexElement
HTMLKeygenElement
HTMLLIElement
HTMLLabelElement
HTMLLegendElement
HTMLLinkElement
HTMLMapElement
HTMLMediaElement
HTMLMetaElement
HTMLMeterElement
HTMLModElement
HTMLOListElement
HTMLObjectElement
HTMLOptGroupElement
HTMLOptionElement
HTMLOptionsCollection
HTMLOutputElement
HTMLParagraphElement
HTMLParamElement
HTMLPictureElement
HTMLPreElement
HTMLProgressElement
HTMLQuoteElement
HTMLScriptElement
HTMLSelectElement
HTMLShadowElement
HTMLSourceElement
HTMLSpanElement
HTMLStyleElement
HTMLTableCaptionElement
HTMLTableCellElement
HTMLTableColElement
HTMLTableDataCellElement
HTMLTableElement
HTMLTableHeaderCellElement
HTMLTableRowElement
HTMLTableSectionElement
HTMLTemplateElement
HTMLTimeElement
HTMLTitleElement
HTMLTrackElement
HTMLUListElement
HTMLUnknownElement
HTMLVideoElement
HashChangeEvent
历史
ImageData
定位
MessageChannel
MessageEvent
MessagePort
Navigator
NavigatorGeolocation
NavigatorID
NavigatorLanguage
NavigatorOnLine
NavigatorPlugins
PageTransitionEvent
Plugin
PluginArray
PopStateEvent
PortCollection
PromiseRejectionEvent
RadioNodeList
Transferable
ValidityState
Window
WindowBase64
WindowEventHandlers
WindowTimers