简体   繁体   English

Javascript window.getSelection()没有给我任何东西

[英]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. 但是,它看起来并不像window.getSelection()一样。

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. 但是我用window.getSelection()尝试过的所有东西都没有给我任何东西。

 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. 您可以尝试使用onmouseup代替onselect。 When you use onselect, the event handler will be invoked the moment the user starts making a selection. 使用onselect时,事件处理程序将在用户开始进行选择时立即被调用。 And since initially nothing is selected, when your event handler runs, window.getSelection() will return an empty string. 而且由于最初没有选择任何内容,因此当您的事件处理程序运行时,window.getSelection()将返回一个空字符串。 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. 如果使用onmouseup,则事件处理程序将在用户做出选择后运行,在这种情况下,当您调用window.getSelection()时,它将正确返回用户做出的选择。

<!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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