简体   繁体   中英

Is the behavior of the caret defined in the standard when arrow keys are pressed?

Inside an editable element (eg <input type='text'/> , <div contenteditable="true"> ) when the caret is in the middle of the text, it will be moved to the start/end of the text if the up/down arrow key is pressed. I would like to know if this behavior is in some standard, as I want to write code relying on this behavior.

By spec, an input type=text cannot be multiline, since it can't have LF or CR characters:

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters. https://html.spec.whatwg.org/dev/input.html#text-(type=text)-state-and-search-state-(type=search)


If your goal is to know the caret position (or the selected range), you can use selectionStart and selectionEnd

 document.querySelector('input').addEventListener('click', function() { console.log( 'is at start:', this.selectionStart === 0, '\n', 'is at end:', this.selectionEnd === this.value.length) })
 <input type="text" value="Foo Bar" />


The only case I can think that that's not the behavior, is when the writing direction is "right to left", which is inverted.

 <input type=text dir=rtl value="Right to Left"> <input type=text dir=ltr value="Left to Right">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM