Home >Web Front-end >JS Tutorial >JS method to get and set the selected text position of TextArea or input text box_javascript skills

JS method to get and set the selected text position of TextArea or input text box_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:08:011420browse

The example in this article describes the method of JS to obtain and set the TextArea or input text box to select the text position. Share it with everyone 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 will be helpful to everyone’s JavaScript programming design.

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