如何使用 JavaScript 获取选定的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14553534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:57:31  来源:igfitidea点击:

How to get selected text with JavaScript

javascriptgetselection

提问by Develop Smith

I'm a little confused why doesn't this code work!

我有点困惑为什么这段代码不起作用!

The HTML Markup:

HTML 标记:

<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda"></div>

The JavaScript code:

JavaScript 代码:

function GetSelectedText () {
if (window.getSelection) {  // all browsers, except IE before version 9
    var range = window.getSelection ();
    alert (range.toString ());
} 
else {
    if (document.selection.createRange) { // Internet Explorer
        var range = document.selection.createRange ();
        alert (range.text);
    }
}
}

var butn = document.getElementById("soda");
butn.onclick = function(){
    GetSelectedText();
}

回答by Tim Down

One problem that you may well be experiencing is that in some browsers (notably IE), by the time the button's clickevent fires, the selection has been destroyed. You can fix this by using the mousedownevent instead (which still allows the selection to be destroyed, but only after the event has been handled), or by making the button unselectable.

您可能会遇到的一个问题是,在某些浏览器(特别是 IE)中,当按钮的click事件触发时,选择已被破坏。您可以通过使用mousedown事件来解决这个问题(它仍然允许销毁选择,但只有在事件被处理之后),或者通过使按钮不可选择

I assume your button is not an actual button input, because this behaviour only happens for regular elements.

我假设您的按钮不是实际的按钮输入,因为这种行为只发生在常规元素上。

Demo: http://jsfiddle.net/L9bvU/1/

演示:http: //jsfiddle.net/L9bvU/1/

function GetSelectedText () {
    if (window.getSelection) {  // all browsers, except IE before version 9
        var range = window.getSelection ();
        alert (range.toString ());
    } 
    else {
        if (document.selection.createRange) { // Internet Explorer
            var range = document.selection.createRange ();
            alert (range.text);
        }
    }
}
span {
    background-color: #ccc;
    padding: 3px;
    border: solid gray 1px;
    
}

*[unselectable="on"] {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

   /*
     Introduced in IE 10.
     See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
   */
   -ms-user-select: none;
   user-select: none;
}
<div contenteditable="true">Please select some of this text and press a button below</div>

<span onclick="GetSelectedText()">Click</span>
<span onmousedown="GetSelectedText()">Mousedown</span>
<span unselectable="on" onclick="GetSelectedText()">Click, unselectable</span>

回答by vlad

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } 
    if (window.document.getSelection) {
        return window.document.getSelection();
    } 
    if (window.document.selection) {
        return window.document.selection.createRange().text;
    }
    return "";  
}
<p onmouseup="getSelectedText(); alert(txt)">
Highlight some of this text
with the mouse select press button end release
to fire the event. </p>


This is my way. You just need to select the text end alert text or anything else.
Does anyone know how OnMouse(event) set for the entire document in html, and it does not have to be directly added to html page.
To be on the other side, as we can change the elements in firebug!>-examples


这是我的方式。您只需要选择文本结束警报文本或其他任何内容。
有谁知道如何在html中为整个文档设置OnMouse(event),并且不必直接添加到html页面。
在另一边,因为我们可以更改 firebug 中的元素!>-例子

回答by Stephen Byrne

Well there are two problems with the above code. -You can't be guaranteed that

那么上面的代码有两个问题。-你不能保证

var butn = document.getElementById("soda");

will work because it may execute before the document is done loading

会起作用,因为它可能会在文档加载完成之前执行

-When you click on another element that's not a button, the selection is lost. If you change the "soda" div to then it will work:

- 当您单击另一个不是按钮的元素时,选择将丢失。如果您将“苏打水”div 更改为那么它将起作用:

<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda" onclick="GetSelectedText()">This will NOT work</div>
<input type="button" onclick="GetSelectedText()" value="This will work"/>
<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda" onclick="GetSelectedText()">This will NOT work</div>
<input type="button" onclick="GetSelectedText()" value="This will work"/>

However I strongly recommend you look at jQuery as the others here have advised; it will make your like a loteasier!

但是,我强烈建议您按照此处其他人的建议查看 jQuery;它会让你像很多更轻松!