How to disable text selection using jQuery?

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


在jQuery 1.8中,可以这样做:

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

If you use jQuery UI, there is a method for that, but it can only handle mouse selection (ie CTRL+A is still working):

$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9

The code is realy simple, if you don't want to use jQuery UI :

$(el).attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', /* you could also put this in a class */
           '-webkit-user-select':'none',/* and add the CSS class here instead */
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

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

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}
链接地址: http://www.djcxy.com/p/41404.html

上一篇: 如何停止点击复选框上的事件冒泡

下一篇: 如何使用jQuery禁用文本选择?