jQuery或jQuery- ui是否有任何功能禁用给定文档元素的文本选择?
当前回答
这里有一个更全面的解决方案来断开选择,并取消一些热键(如Ctrl+a和Ctrl+c)。测试:Cmd+a和Cmd+c
(function($){
$.fn.ctrlCmd = function(key) {
var allowDefault = true;
if (!$.isArray(key)) {
key = [key];
}
return this.keydown(function(e) {
for (var i = 0, l = key.length; i < l; i++) {
if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
allowDefault = false;
}
};
return allowDefault;
});
};
$.fn.disableSelection = function() {
this.ctrlCmd(['a', 'c']);
return this.attr('unselectable', 'on')
.css({'-moz-user-select':'-moz-none',
'-moz-user-select':'none',
'-o-user-select':'none',
'-khtml-user-select':'none',
'-webkit-user-select':'none',
'-ms-user-select':'none',
'user-select':'none'})
.bind('selectstart', false);
};
})(jQuery);
并调用示例:
$(':not(input,select,textarea)').disableSelection();
jsfiddle.net/JBxnQ/
这对于旧版本的FireFox来说可能也不够(我不知道是哪个)。如果所有这些都不起作用,请添加以下内容:
.on('mousedown', false)
其他回答
如果你使用jQuery UI,有一个方法,但它只能处理鼠标选择(即CTRL+ a仍然有效):
$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9
代码非常简单,如果你不想使用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; });
我已经尝试了所有的方法,这一个对我来说是最简单的,因为我使用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;
}
在适当的情况下,一种解决方案是对您不想选择的文本使用<按钮>。如果你在某个文本块上绑定到click事件,并且不希望该文本是可选择的,那么将其更改为按钮将改善语义,也会阻止文本被选择。
<button>Text Here</button>
最好和最简单的方法,我发现它,防止ctrl + c,右键单击。在本例中,我屏蔽了所有内容,因此不需要指定任何内容。
$(document).bind("contextmenu cut copy",function(e){
e.preventDefault();
//alert('Copying is not allowed');
});