2010-11-24 24 views
0

单击“span”时,我想要在文本区域中选择文本。当我点击按钮选择的作品,但不是当我点击跨度。
也许是因为选择在点击span时丢失了,但是点击按钮时没有发生? 如何解决它?只有当在IE中单击跨度时从textarea中检索选定的文本

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!

Online Example

更新:

这是我如何做到这一点,在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); 
} 

回答

0

是的,这也正是它:由当时的单击事件触发时,选择已丢失。如果您使用onmousedown而不是onclick,它将起作用。

UPDATE

在IE只能是以下属性添加到<span>另一种替代。这将使得它不能选择防止跨度从影响的选择:

unselectable="on" 

更新2

在其他浏览器,以获得所选文本的方式是使用selectionStartselectionEnd属性:

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

但它为什么与按钮一起工作? – urker 2010-11-24 17:00:46

相关问题