鼠标选中文字的兼容

function getSelectedText() {
    var txt = ""; 
    if (window.getSelection) { 
        txt = window.getSelection(); 
    } else if (window.document.getSelection) { 
        txt = window.document.getSelection(); 
    } else if (window.document.selection) {
        txt = window.document.selection.createRange().text; 
    } 
        return txt; 
    } 

自己测过,主流浏览器都是支持的,可以兼容到ie5!!!

input 输入框中如果想要获取鼠标选中的内容,代码如下

var oInput = document.getElementById('input');
oInput.onmouseup = function(){
    alert(oInput.value.substring(input.selectionStart,input.selectionEnd));
}

目前只能兼容到ie9

原文地址:https://www.cnblogs.com/chenzhiyu/p/8241377.html