如何使用范围接口双击选择一个单词?

时间:2019-05-09 12:42:40

标签: javascript range selection

例如:

<span>"This is s"<span style="color:1abc9c">ent</span>"e<strong>nc</strong>"e to be select"</span>

句子是这样的:“这是要选择的句子” 。现在,当我在单词句子内的任意位置双击时,应该选择该单词。如何选择这个词?

1 个答案:

答案 0 :(得分:1)

如果您要双击句子中的任何单词以选择单词“句子” ,但不能选择整个句子

let sentence = document.getElementsByClassName('sentence');
let word = document.getElementById('word');

Array.from(sentence).forEach(sentence =>
  sentence.addEventListener('dblclick', (e) => {
    e.preventDefault();
    let sel = window.getSelection();
    sel.removeAllRanges();
    let range = document.createRange();
    range.selectNode(word);
    sel.addRange(range);
  })
);
.sentence {
  user-select: none;
  cursor: text;
}
<span class="sentence">This is the </span><span id="word">sentence</span><span class="sentence"> to be selected.</span>

或者,如果您要双击句子中的任何单词以选择单词“ <句子>”,则选择:

let sentence = document.getElementById('sentence');
let word = document.getElementById('word');

sentence.addEventListener('dblclick', (e) => {
  e.preventDefault();
  let sel = window.getSelection();
  sel.removeAllRanges();
  let range = document.createRange();
  range.selectNode(word);
  sel.addRange(range);
});
<span id="sentence">This is the <span id="word">sentence</span> to be selected.</span>

或者,如果您要单击句子中的任何单词以选择单词“句子”

let sentence = document.getElementById('sentence');
let word = document.getElementById('word');

sentence.addEventListener('dblclick', () => {
  let sel = window.getSelection();
  sel.removeAllRanges();
  let range = document.createRange();
  range.selectNode(word);
  sel.addRange(range);
});
<span id="sentence">This is the <span id="word">sentence</span> to be selected.</span>

或者,如果您要单次点击,请选择“句子”

let word = document.getElementById('word');

word.addEventListener('click', () => {
  let sel = window.getSelection();
  sel.removeAllRanges();
  let range = document.createRange();
  range.selectNode(word);
  sel.addRange(range);
});
This is the <span id="word">sentence</span> to be selected.

或者如果您想单击“句子” 上的以使用带有user-select CSS 将其选中:

span {
  user-select: all;
}
This is the <span>sentence</span> to be selected.