2010-11-24 6 views
0

「スパン」をクリックすると、テキストエリア内で選択したテキストを取得したいと考えています。ボタンをクリックすると、選択範囲は有効になりますが、スパンをクリックしても機能しません。
スパンがクリックされたときに選択が失われるかもしれないが、ボタンをクリックしても起こっていないのだろうか? 修正方法?IEでスパンをクリックしたときにテキストエリアから選択したテキストを取得する

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

はい、それはまさにそれだ:時間によるクリックイベントが発生し、選択がされています失われたonclickの代わりにonmousedownを使用すると機能します。

UPDATE

のみ<span>に次の属性を追加することですIEで動作する別の方法。これは、それが選択できないことによって、選択に影響を与えることからスパンを防ぐ:

unselectable="on" 

UPDATE他のブラウザで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

+0

mousedownは私が望むふるまいではありません...私は他のボタンのようにマウスアップしてもらいたいです。 – urker

+0

OK。ボタンはちょっと違った働きをするので、選択には影響しないと思う。とにかく、私の答えを更新... –

関連する問題