简体   繁体   中英

The opposite to window.getSelection()

I am selecting a text to copy it by using window.getSelection().addRange(range) :

  var targetelement = document.getElementById("someid"), 
  range = document.createRange();
  range.selectNode(targetelement);
  window.getSelection().addRange(range);
  document.execCommand('copy')

It works, but the browser(firefox) selects the text inside the tag after the completion of the code. How can I diselect it? Is there some kind of opposite to window.getSelection function or method?

<div id="someid">
This is a test man
</div>

<div id="empty">
</div>


<script>
    var targetelement = document.getElementById("someid");
    var  range = document.createRange();
  range.selectNode(targetelement);
  window.getSelection().addRange(range);
  document.execCommand('copy');  

   window.getSelection().removeAllRanges();
</script>

https://jsfiddle.net/s1teLukn/5/

复制后,触发焦点模糊到该输入字段以取消选择文本。

This old code works in all browsers:

var sel = window.getSelection ? window.getSelection() : document.selection;

if (sel) {
    if (sel.removeAllRanges) {
        sel.removeAllRanges();
    } else if (sel.empty) {
        sel.empty();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM