开发者

Retrieving selected text from textarea when span is clicked in IE

I want to get the selected text within the text area when 'span' is clicked. When I click button the selection works but not when I click on span.

Maybe because the selection is lost when span is clicked,开发者_高级运维 but it's not happening when button is clicked? How to fix it?

function Copy() {
  var theSelection = document.selection.createRange();
  alert(theSelection.text);           
}

 <div>
    <span class="Icon" onclick="Copy();"></span> <input type="button" value="Copy" onclick="Copy();" style="float:left;" />  
 </div>
 <div style="clear:both;">
    <textarea rows="2" cols="20" style="height:370px;width:800px;"></textarea> 
 </div>

IE only!

Online Example

Update:

This is how I do it in firefox:

if (window.getSelection){ // Firefox, Opera, Safari

   var textbox = document.getElementById("box");
   textbox.focus();
   theSelection = document.activeElement.value.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);

alert(theSelection);
}


Yes, that's exactly it: by the time the click event fires, the selection has been lost. It will work if you use onmousedown instead of onclick.

UPDATE

Another alternative that works in IE only is to add the following attribute to the <span>. This prevents the span from affecting the selection by making it unselectable:

unselectable="on"

UPDATE 2

In other browsers, the way to get the selected text is to use the selectionStart and selectionEnd properties:

function Copy() {
    var textbox = document.getElementById("box");
    textbox.focus();
    var selectedText = "";
    if (typeof textbox.selectionStart == "number") {
        selectedText = textbox.value.slice(textbox.selectionStart, textbox.selectionEnd);
    } else if (document.selection) {
        selectedText = document.selection.createRange().text;
    }
    alert(selectedText);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜