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


当前回答

在jQuery 1.8中,可以这样做:

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

其他回答

在jQuery 1.8中,可以这样做:

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

我已经尝试了所有的方法,这一个对我来说是最简单的,因为我使用IWebBrowser2,没有10个浏览器来竞争:

document.onselectstart = new Function('return false;');

非常适合我!

我发现这个答案(防止文本表高亮显示)最有帮助,也许它可以与提供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();
        $(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");
        });