如何使用JavaScript获取选定的文本 [英] How to get selected text with JavaScript

查看:90
本文介绍了如何使用JavaScript获取选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

HTML标记:

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

JavaScript代码:

The JavaScript code:

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();
}

推荐答案

您可能会遇到的一个问题是,在某些浏览器(尤其是IE)中,当按钮的click事件触发时,选择已被执行.毁了.您可以通过改用mousedown事件(仍允许销毁选择,但仅在处理事件之后)来解决此问题,或者通过

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

我认为您的按钮不是实际的按钮输入,因为此行为仅在常规元素中发生.

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

演示: 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>

这篇关于如何使用JavaScript获取选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆