简体   繁体   中英

Javascript window.getSelection() not giving me anything

So I'm going to look like a big idiot, but I can't get this to work. All it needs to do is pop up an alert telling you what text you selected. However, it doesn't look like window.getSelection() is going anything.

When I concatenate a regular string variable into the alert, it displays. But everything I've tried with window.getSelection() isn't giving me anything.

 function myFunction() { var selObj = window.getSelection(); var selText = selObj.toString(); alert("You selected " + selText + "!"); } 
 Select some of the text : <input type="text" value="Hello world!" onselect="myFunction()"> 

You could try using onmouseup instead of onselect. When you use onselect, the event handler will be invoked the moment the user starts making a selection. And since initially nothing is selected, when your event handler runs, window.getSelection() will return an empty string. If you use onmouseup, the event handler will run after the user has made their selection, in which case, when you invoke window.getSelection(), it will correctly return the selection that the user has made.

<!DOCTYPE html>
<html>
<body>

    Select some of the text: <input type="text" value="Hello world!" onmouseup="myFunction()">

<script>
    function myFunction() {
       var selObj = window.getSelection();
       var selText = selObj.toString();
       alert("You selected " + selText + "!");
    }
</script>

</body>
</html>

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