简体   繁体   中英

Window.getSelection() onchange not working

I am trying to call a function when the selected text on a website changes.

Right now nothing happens:

<textarea name="" id="" cols="30" rows="10"></textarea>
<script>    
var selection = null;

window.getSelection().toString().addEventListener('change', function() {
    selection = window.getSelection().toString();
  alert(selection);
});
</script>

Try like this :

 document.onselectionchange = () => {

     let text = window.getSelection().toString();

     console.log(text)

  };

You could use document.onselectionchange that will be fired if the selectionchange , like :

 document.onselectionchange = function() { console.log(window.getSelection().toString()); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea name="" id="" cols="30" rows="10"></textarea> 

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