2

次の関数を使用して選択したテキストを取得しています。すべての主要なブラウザーで非常にうまく機能しますが、バージョン 9 より前の IE では正しく機能しません!

function getSelected() {
    var t = '';
 if (window.getSelection) {
     t = window.getSelection();
} else if (document.getSelection) {
    t = document.getSelection();
    t = t.toString();
} else if (document.selection) {
    t = document.selection.createRange();
    t = t.text;
}
    return t;
}

var txt = getSelected();

バージョン 9 より前の IE では、変数「txt」にテキストが保存されないという問題があります。

4

1 に答える 1

0

デモ:http: //jsfiddle.net/ytJ35/

以下は、javascriptを使用して選択したHTMLテキストを取得する方法から抜粋したものです。

このjavascript関数はIE7以降で機能します。

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}

Chrome、IE10、IE6、IE7でテスト済み

于 2013-01-29T06:50:19.667 に答える