【问题标题】:How to select text in IE?如何在 IE 中选择文本?
【发布时间】:2013-01-28 22:20:46
【问题描述】:

我正在使用以下函数来获取选定的文本,它在所有主流浏览器中运行良好,但在 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();

这里的问题是 IE 在版本 9 之前它不会在变量“txt”中存储任何文本

【问题讨论】:

标签: javascript internet-explorer getselection


【解决方案1】:

演示: http://jsfiddle.net/ytJ35/

以下摘自How to get selected html text with javascript?

这个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 中测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-09
    • 2010-12-27
    • 1970-01-01
    • 2013-10-14
    • 2011-09-07
    • 2015-06-15
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多