如何阻止文本被选中?

Ben*_*ock 12 javascript jquery cross-browser textselection

在我的网络应用程序中,用户有时可以多次单击相同的按钮,跳过消息和事物,从而导致</a>选择.

那么如何使用Javascript(jQuery)来防止这种情况

Blo*_*sie 29

你不需要脚本,这里是css:

-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
Run Code Online (Sandbox Code Playgroud)

  • 问的人可能预先决定他们想要使用JS,但你的答案远比任何脚本好.+1 (2认同)

Mar*_*ski 2

这个解决方案对我有用: http ://chris-barr.com/entry/disable_text_selection_with_jquery/

$(function(){
    $.extend($.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){return false;});
            }else{//Opera, etc.
                $(this).mousedown(function(){return false;});
            }
        });
    });
    $('.noSelect').disableTextSelect();//No text selection on elements with a class of 'noSelect'
});
Run Code Online (Sandbox Code Playgroud)

  • 对于那些遇到这个答案的人来说,Blowsie 描述的 CSS 方法是一个更好的解决方案(并且与链接的 jQuery 答案做同样的事情)。 (2认同)