JS gets and sets the method to select the text location of the TextArea or input text box
- 2020-05-17 04:48:52
- OfStack
This example shows how to get and set JS to TextArea or input text boxes to select the text location. Share with you for your reference. The specific implementation method is as follows:
function getPos(el) {
var range, textRange, duplicate
el.focus()
if ( el.selectionStart ) return el.selectionStart
else if ( document.selection ) { // IE
range = document.selection.createRange()
if ( range == null ) return el.value.length
textRange = el.createTextRange()
duplicate = textRange.duplicate()
textRange.moveToBookmark(range.getBookmark())
duplicate.setEndPoint('EndToStart', textRange)
return duplicate.text.length
}
}
function setPos(el, pos) {
var range
el.focus()
if ( el.setSelectionRange )
el.setSelectionRange(pos, pos)
else if ( el.createTextRange ) {
range.collapse(true)
range.moveEnd('character', pos)
range.moveStart('character', pos)
range.select()
}
}
I hope this article has been helpful to your javascript programming.