js 监听文字鼠标选中

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

直接查看他的源码,主要是使用了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,双击会触发鼠标抬起事件,所以会输出两遍;选中文本在取消选中也会输出。。


转载:https://blog.csdn.net/u014291497/article/details/52717353

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值