如何使用JavaScript获取所选文本

Dev*_*ith 3 javascript getselection

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

HTML标记:

<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda"></div>
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*own 7

您可能遇到的一个问题是,在某些浏览器(尤其是IE)中,当按钮的click事件触发时,选择已被破坏.您可以通过使用mousedown事件来修复此问题(这仍然允许销毁选择,但仅在事件处理完毕后),或者使按钮不可选.

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

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


小智 5

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 "";  
}
Run Code Online (Sandbox Code Playgroud)
<p onmouseup="getSelectedText(); alert(txt)">
Highlight some of this text
with the mouse select press button end release
to fire the event. </p>
Run Code Online (Sandbox Code Playgroud)


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