admin管理员组文章数量:1425740
I have this code working, i just want to understand why do i need to use removeAllRanges
at the start. Did the sel had a ranges in it automatically when initialized?
function setCaret(boolean_position) {
var range = document.createRange();
var sel = window.getSelection();
range.selectNodeContents($('#board_code')[0]);
range.collapse(boolean_position);
sel.removeAllRanges();
sel.addRange(range);//setting the caret position
}
I have this code working, i just want to understand why do i need to use removeAllRanges
at the start. Did the sel had a ranges in it automatically when initialized?
function setCaret(boolean_position) {
var range = document.createRange();
var sel = window.getSelection();
range.selectNodeContents($('#board_code')[0]);
range.collapse(boolean_position);
sel.removeAllRanges();
sel.addRange(range);//setting the caret position
}
Share
Improve this question
edited Jan 28, 2017 at 13:37
Robin
7,9042 gold badges34 silver badges49 bronze badges
asked Jun 5, 2013 at 6:48
user2454455user2454455
1 Answer
Reset to default 5Yes, the selection retrieved from window.getSelection()
isn't an empty instance like the range created by document.createRange()
. Notice the difference in these methods names - one creates new instance and second gets the instance.
The reason is simple - you can have multiple range instances, every containing different positions. But there's only one selection per document.
Therefore, before adding range, usually you have to remove old ranges that are currently selected. Unless, of course, that you want to extend current selection.
Update: As Tim correctly pointed out, only Firefox supports multiple selection ranges. This means that only on Firefox you're able to select more than one piece of DOM at a time - e.g. you can select table's column or add more selections using CTRL key.
Therefore, only Firefox requires that you execute removeAllRanges()
before adding next ones. Other browsers will automatically remove old ranges.
本文标签: javascriptWhy use removeAllRAnges() at the start of a selectionStack Overflow
版权声明:本文标题:javascript - Why use removeAllRAnges() at the start of a selection? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745391936a2656637.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论