Skip to content

JS 自动选中 div 内文本

Published: at 05:43 PMSuggest Changes

问题

有一段文本,想要自动选中,代码如下

<div class="text">这是一段文字</div>

解决

const text = document.querySelector('.text')
text.addEventListener('click', () => {
  const range = document.createRange()
  range.selectNodeContents(text)
  const selection = window.getSelection()
  selection.removeAllRanges()
  selection.addRange(range)
})

封装成函数

function SelectText(element) {
  const doc = document
  const text = element
  let range, selection

  if (doc.body.createTextRange) {
    range = document.body.createTextRange()
    range.moveToElementText(text)
    range.select()
  } else if (window.getSelection) {
    selection = window.getSelection()
    range = document.createRange()
    range.selectNodeContents(text)
    selection.removeAllRanges()
    selection.addRange(range)
  }
}

Previous Post
Kibana 国际化 (i18n) 中文设置
Next Post
CSS 字体呈现优化