0%

JS 自动选中 div 内的文本

问题

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

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

解决

1
2
3
4
5
6
7
8
const text = document.querySelector('.text')
text.addEventListener('click', () => {
const range = document.createRange()
range.selectNodeContents(text)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
})

封装成函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)
}
}