The trick is to use removeAllRanges()
on your selection before adding your new range using addRange(range)
. Here is an example when using it to select all content of elem
:
selection = window.getSelection(); // Save the selection.
range = document.createRange();
range.selectNodeContents(elem);
selection.removeAllRanges(); // Remove all ranges from the selection.
selection.addRange(range); // Add the new range.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…