首页 > 解决方案 > Javascript,检测是文本实际上未选中

问题描述

试图弄清楚如何正确检测是否未选择文本。

在 Firefox 中,您可以突出显示文本,单击内部并完全取消选择。

在 Chrome/Chromium 中,如果您在突出显示的文本内单击,该文本仍被视为已选中,直到再次单击(即使视觉突出显示消失)。

我们如何解决这个问题?

JS/jQuery 代码:

function getSelected() 
{
    var return_text;
    if (window.getSelection) 
    {
        return_text = window.getSelection();
    }
    else if (document.getSelection) 
    {
        return_text = document.getSelection();
    }
    return return_text;
}

$(document).on('click', "div", function(e) 
{
        var selection = getSelected();
        var selectedText = selection.toString();
        console.log(selectedText);
});

用于测试的 HTML:

<div>
This is some text. Open your F12 console and select some text to test me<br />
<br />
In Chromium, the selected text stays until you click twice even though it is visually unselected on the first click. In Firefox, it clears properly on one click.<br />
<br />
Why is Chromium doing this? It's causing really annoying behaviour.
</div>

示例:https ://jsfiddle.net/7sf35c4j/

据我所知,这使得在 Chrome/Chromium 中基本上不可能准确地知道什么时候取消选择了???

标签: javascriptjquerychromium

解决方案


推荐阅读