jQuery或jQuery- ui是否有任何功能禁用给定文档元素的文本选择?


当前回答

以下将禁用所有常见浏览器(IE, Chrome, Mozilla, Opera和Safari)中所有类的“item”的选择:

$(".item")
        .attr('unselectable', 'on')
        .css({
            'user-select': 'none',
            'MozUserSelect': 'none'
        })
        .on('selectstart', false)
        .on('mousedown', false);

其他回答

        $(document).ready(function(){
            $("body").css("-webkit-user-select","none");
            $("body").css("-moz-user-select","none");
            $("body").css("-ms-user-select","none");
            $("body").css("-o-user-select","none");
            $("body").css("user-select","none");
        });

最好和最简单的方法,我发现它,防止ctrl + c,右键单击。在本例中,我屏蔽了所有内容,因此不需要指定任何内容。

$(document).bind("contextmenu cut copy",function(e){
    e.preventDefault();
    //alert('Copying is not allowed');
});

在jQuery 1.8中,可以这样做:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

我发现这个答案(防止文本表高亮显示)最有帮助,也许它可以与提供IE兼容性的另一种方式结合起来。

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

我认为这段代码可以在所有浏览器上运行,所需的开销最少。它实际上是上述所有答案的混合体。如果你发现了窃听器,请告诉我!

添加CSS:

.no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}

添加jQuery:

(function($){
    $.fn.disableSelection = function() 
    {       
        $(this).addClass('no_select');              
        if($.browser.msie)
        {
            $(this).attr('unselectable', 'on').on('selectstart', false);            
        }
    return this;            
};
})(jQuery);

可选:要禁用所有子元素的选择,您可以将IE块更改为:

$(this).each(function() {
    $(this).attr('unselectable','on')
    .bind('selectstart',function(){ return false; });
});

用法:

$('.someclasshere').disableSelection();