3

ドキュメントでテキストが選択された後に関数を呼び出したい。次のコードが機能していません

var showSelWin = document.getElementById('innerwindow');
var txt = ' ';
if (document.getSelection) function(){
txt = document.getSelection();
showSelWin.innerHTML = txt;
document.body.insertBefore(showSelWin, document.body.firstChild);}
4

1 に答える 1

2

document.getSelection メソッドの動作は、Google Chrome、Safari、および Internet Explorer では、Firefox および Opera とは異なります。

Firefox および Opera では文字列を返し、Google Chrome、Safari および Internet Explorer では selectionRange オブジェクトを返します (document.getSelection メソッドは、Google Chrome、Safari および Internet Explorer の window.getSelection メソッドと同じです)。

バージョン 9 以降の Firefox、Opera、Google Chrome、Safari、Internet Explorer では、window.getSelection メソッドと、window.getSelection メソッドによって返される selectionRange オブジェクトの toString メソッドを使用して、選択範囲のテキスト コンテンツを取得します。

古いバージョンの Internet Explorer では、選択オブジェクトの createRange メソッドと、createRange メソッドによって返される TextRange オブジェクトの text プロパティを使用して、選択範囲のテキスト コンテンツを取得します。

あなたのための実用的なサンプル: http://jsfiddle.net/uX628/

function GetSelectedText () {
    if (document.getSelection) {    // all browsers, except IE before version 9
        var sel = document.getSelection ();
        // sel is a string in Firefox and Opera,
        // and a selectionRange object in Google Chrome, Safari and IE from version 9
        // the alert method displays the result of the toString method of the passed object
        alert (sel);
    }
    else {
        if (document.selection) {   // Internet Explorer before version 9
            var textRange = document.selection.createRange ();
            alert (textRange.text);
        }
    }
}
于 2012-03-02T13:57:25.263 に答える