检测文本是否在鼠标上突出显示jQuery

Detect if text is highlighted on mouse up jQuery

本文关键字:显示 jQuery 鼠标 文本 是否 检测      更新时间:2023-09-26

如何使用jQuery检测是否有任何文本高亮显示。

我试过了:

$(document).mouseup(function(){
    if(typeof window.getSelection!="undefined"){
        console.log("text highlighted");
    }
});

但它不起作用,每次鼠标点击时console.log()都会启动,即使没有任何突出显示。。

试试这个:

$(document).mouseup(function(){
    var highlightedText = "";
    if (window.getSelection) {
        highlightedText = window.getSelection().toString();
    } 
    else if (document.selection && document.selection.type != "Control") {
        highlightedText = document.selection.createRange().text;
    }
    if(highlightedText != "")
        console.log("text highlighted.");
});
$(document).on("mouseup", function() {
    if (window.getSelection().toString() != "") {
        console.log("text highlighted :" + window.getSelection().toString());
    }
});

这是的另一种方法