获取浏览器中鼠标选中的文本内容

如果你在浏览器中安装了翻译插件的话,控制台可能会输出你选中的文本内容,那么这是如何做到的呢?

直接查看他的源码,主要是使用了window.getSelection 这个属性

所以我们也可以仿照着写一个函数,用来监听鼠标双击,或者鼠标抬起事件:

// 监听双击事件
document.addEventListener("dblclick", doubleClick, true);

// 监听释放鼠标按钮事件
document.addEventListener("mouseup", mouseUp, true);

// 双击处理函数
function doubleClick() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    if ("" != text) {
        console.log(text);
    }

}

// 释放鼠标处理函数
function mouseUp() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    if ("" != text) {
        console.log(text);
    }
}

有点BUG,双击会触发鼠标抬起事件,所以会输出两遍;选中文本在取消选中也会输出。。

你可能感兴趣的:(javascript)