问题
有一段文本,想要自动选中,代码如下
<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)
}
}