JavaScript:通过双击禁用文本选择

发布于 2024-09-30 20:04:46 字数 197 浏览 4 评论 0原文

当双击 html 页面时,大多数浏览器都会选择您双击的单词(或三次单击的段落)。有没有办法摆脱这种行为?

请注意,我不想通过单击+拖动来禁用常规选择;即 jQuery UI 的 $('body').disableSelection()document.onselectstart DOM 事件不是我想要的。

When double-clicking on a html page most browsers select the word you double-click on (or the paragraph you triple-click on). Is there a way to get rid of this behavior?

Note that I do not want to disable regular selection via single-click+dragging; i.e. jQuery UI's $('body').disableSelection() and the document.onselectstart DOM event are not what I want.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心欲静而疯不止 2024-10-07 20:04:46

我担心您无法阻止选择本身成为浏览器的“本机行为”,但您可以在选择后立即清除选择:

<script type="text/javascript">
document.ondblclick = function(evt) {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}
</script>

编辑:还可以防止通过“三次单击”选择整个段落,这是所需的代码:

var _tripleClickTimer = 0;
var _mouseDown = false;

document.onmousedown = function() {
    _mouseDown = true;
};

document.onmouseup = function() {
    _mouseDown = false;
};

document.ondblclick = function DoubleClick(evt) {
    ClearSelection();
    window.clearTimeout(_tripleClickTimer);

    //handle triple click selecting whole paragraph
    document.onclick = function() {
        ClearSelection();
    };

    _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
};

function RemoveDocumentClick() {
    if (!_mouseDown) {
        document.onclick = null; 
        return true;
    }

    _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
    return false;
}

function ClearSelection() {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}​

实时测试用例

应该是跨浏览器的,请报告任何无法正常工作的浏览器。

I fear you can't prevent the selection itself being "native behavior" of the browser, but you can clear the selection right after it's made:

<script type="text/javascript">
document.ondblclick = function(evt) {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}
</script>

Edit: to also prevent selecting whole paragraph by "triple click", here is the required code:

var _tripleClickTimer = 0;
var _mouseDown = false;

document.onmousedown = function() {
    _mouseDown = true;
};

document.onmouseup = function() {
    _mouseDown = false;
};

document.ondblclick = function DoubleClick(evt) {
    ClearSelection();
    window.clearTimeout(_tripleClickTimer);

    //handle triple click selecting whole paragraph
    document.onclick = function() {
        ClearSelection();
    };

    _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
};

function RemoveDocumentClick() {
    if (!_mouseDown) {
        document.onclick = null; 
        return true;
    }

    _tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
    return false;
}

function ClearSelection() {
    if (window.getSelection)
        window.getSelection().removeAllRanges();
    else if (document.selection)
        document.selection.empty();
}​

Live test case.

Should be cross browser, please report any browser where it's not working.

故人爱我别走 2024-10-07 20:04:46

以下内容适用于当前的 Chrome (v56)、Firefox (v51) 和 MS Edge (v38) 浏览器。

var test = document.getElementById('test');
test.addEventListener('mousedown', function(e){
    if (e.detail > 1){
        e.preventDefault();
    }
});
<p id="test">This is a test area</p>

MouseEvent.detail 属性跟踪 当前点击计数,可用于确定事件是两次、三次还是多次点击。

遗憾的是,Internet Explorer 在超时后不会重置计数器,因此您不会获得突发点击次数,而是会获得自页面加载以来用户点击次数的计数。

The following works for me in the current Chrome (v56), Firefox (v51) and MS Edge (v38) browsers.

var test = document.getElementById('test');
test.addEventListener('mousedown', function(e){
    if (e.detail > 1){
        e.preventDefault();
    }
});
<p id="test">This is a test area</p>

The MouseEvent.detail property keeps track of the current click count which can be used to determine whether the event is a double, tripple, or more click.

Internet explorer unfortunately does not reset the counter after a timeout period so instead of getting a count of burst-clicks you get a count of how many times the user has clicked since the page was loaded.

风为裳 2024-10-07 20:04:46

只需将其放在 css 感兴趣的部分即可

 -moz-user-select     : none;
 -khtml-user-select   : none;
 -webkit-user-select  : none;
 -o-user-select       : none;
 user-select          : none;

Just put this on the css interested section

 -moz-user-select     : none;
 -khtml-user-select   : none;
 -webkit-user-select  : none;
 -o-user-select       : none;
 user-select          : none;
狼性发作 2024-10-07 20:04:46

如果您确实想在双击时禁用选择,而不仅仅是随后删除选择(对我来说看起来很难看),则需要在第二个 mousedown 事件中返回 false ( ondblclick 不起作用,因为选择是在 mousedown 上进行的)。

**如果有人根本不想选择,最好的解决方案是使用 CSS user-select : none; 就像 Maurizio Battaghini 提出的那样。

// set to true if you want to disable also the triple click event
// works in Chrome, always disabled in IE11
var disable_triple_click = true;

// set a global var to save the timestamp of the last mousedown
var down = new Date().getTime();
var old_down = down;

jQuery(document).ready(function($)
{
    $('#demo').on('mousedown', function(e)
    {
        var time = new Date().getTime();

        if((time - down) < 500 && 
        (disable_triple_click || (down - old_down) > 500))
        {
            old_down = down;
            down = time;

            e.preventDefault(); // just in case
            return false; // mandatory
        }

        old_down = down;
        down = time;
    });
});

现场演示

重要通知:我将灵敏度设置为 500 毫秒,但双击灵敏度(检测为双击的两次单击之间的最长时间)可能会因操作系统和浏览器的不同而有所不同,并且通常是用户可配置的。 - api.jquery.com

在 Chrome 和 IE11 中测试。

If you really want to disable selection on double-click and not just remove the selection afterwards (looks ugly to me), you need to return false in the second mousedown event (ondblclick won't work because the selection is made onmousedown).

**If somebody wants no selection at all, the best solution is to use CSS user-select : none; like Maurizio Battaghini proposed.

// set to true if you want to disable also the triple click event
// works in Chrome, always disabled in IE11
var disable_triple_click = true;

// set a global var to save the timestamp of the last mousedown
var down = new Date().getTime();
var old_down = down;

jQuery(document).ready(function($)
{
    $('#demo').on('mousedown', function(e)
    {
        var time = new Date().getTime();

        if((time - down) < 500 && 
        (disable_triple_click || (down - old_down) > 500))
        {
            old_down = down;
            down = time;

            e.preventDefault(); // just in case
            return false; // mandatory
        }

        old_down = down;
        down = time;
    });
});

Live demo here

Important notice: I set the sensitivity to 500ms but Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable. - api.jquery.com

Tested in Chrome and IE11.

爱你是孤单的心事 2024-10-07 20:04:46

只是为了把这个扔出去,但这是我放入页面的代码,我希望用户能够快速点击。但是,这也会禁用标准的单击拖动文本选择。

document.body.onselectstart = function() {
    return false;
}
document.body.style.MozUserSelect = "none";
if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
    document.body.onmousedown = function() {
        return false;
    }
}

似乎对我来说效果很好。

Just to throw this out there, but here's the code I slap into my pages where I expect users to be clicking rapidly. However, this will also disable standard click-n-drag text selection.

document.body.onselectstart = function() {
    return false;
}
document.body.style.MozUserSelect = "none";
if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
    document.body.onmousedown = function() {
        return false;
    }
}

Seems to work well for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文