简体   繁体   中英

Javascript: Get Selected Text From Textarea in IE8

I'm trying to read in the value of selected text within a text area. Here is my code:

function readSelected(id)
{ 
    textarea = document.getElementById(id);
    if (document.selection)
    { //Code for IE
        textarea.focus();
        sel = document.selection.createRange();
        alert(sel.text);
    }
    else 
    {  // Code for Mozilla Firefox
        var len = textarea.value.length;
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;

        var scrollTop = textarea.scrollTop;
        var scrollLeft = textarea.scrollLeft;

        sel = textarea.value.substring(start, end);

        alert(sel);
    }
}

HTML:

<textarea id="txt1" rows="10"></textarea> 
<a onclick="readSelected('txt1');">Get Selected</a>

When you click the button, a popup should occur telling you what the selected text is.

The code works in Firefox, but I can't get it to work in IE8.

The problem is that clicking on the <a> element destroys the selection. You could use an unselectable button instead:

<input type="button" value="get" onclick="readSelected('txt1');" unselectable="on">

There are other minor issues with your code

  1. You should declare all your variables, otherwise they end up leaking into the global scope. sel and textarea are the offenders here.
  2. scrollTop and scrollLeft are redundant.
  3. You should test for the selectionStart and selectionEnd properties first, since they're the standard (HTML 5 specifies them and IE 9 will support them).

Here's my rewritten version:

function readSelected(id) {
    var sel = "", el = document.getElementById(id);
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        sel = el.value.slice(el.selectionStart, el.selectionEnd);
    } else if (document.selection && document.selection.createRange) {
        el.focus();
        sel = document.selection.createRange().text;
    }
    alert(sel);
}

您是否尝试过onmousedown而不是onclick

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