2010-11-24 21 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

相關問題