Javascript 如何在IE中选择文本?

Javascript 如何在IE中选择文本?,javascript,internet-explorer,getselection,Javascript,Internet Explorer,Getselection,我正在使用下面的函数来获取选中的文本,它在所有主流浏览器中都运行得很好,但是在IE 9之前的版本中它不能正常工作 function getSelected() { var t = ''; if (window.getSelection) { t = window.getSelection(); } else if (document.getSelection) { t = document.getSelection(); t = t.toString(); }

我正在使用下面的函数来获取选中的文本,它在所有主流浏览器中都运行得很好,但是在IE 9之前的版本中它不能正常工作

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”中存储任何文本。

DEMO:

下表摘自

此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中测试,可能会重复,看看这是否对您有帮助。我的IE问题此代码适用于所有浏览器,但不适用于IE