jQuery或jQuery- ui是否有任何功能禁用给定文档元素的文本选择?
当前回答
我发现这个答案(防止文本表高亮显示)最有帮助,也许它可以与提供IE兼容性的另一种方式结合起来。
#yourTable
{
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
其他回答
CHROME 1线解决方案:
body.style.webkitUserSelect = "none";
和FF:
body.style.MozUserSelect = "none";
IE需要设置“unselectable”属性(详细信息在底部)。
我在Chrome中测试了这个,它可以工作。此属性是继承的,因此在body元素上设置它将禁用整个文档中的选择。
详情:http://help.dottoro.com/ljrlukea.php
如果你正在使用闭包,只需调用这个函数:
goog.style.setUnselectable(myElement, true);
它透明地处理所有浏览器。
非ie浏览器是这样处理的:
goog.style.unselectableStyle_ =
goog.userAgent.GECKO ? 'MozUserSelect' :
goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
null;
定义: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html
IE部分是这样处理的:
if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
for (var i = 0, descendant; descendant = descendants[i]; i++) {
descendant.setAttribute('unselectable', value);
}
}
在适当的情况下,一种解决方案是对您不想选择的文本使用<按钮>。如果你在某个文本块上绑定到click事件,并且不希望该文本是可选择的,那么将其更改为按钮将改善语义,也会阻止文本被选择。
<button>Text Here</button>
以下将禁用所有常见浏览器(IE, Chrome, Mozilla, Opera和Safari)中所有类的“item”的选择:
$(".item")
.attr('unselectable', 'on')
.css({
'user-select': 'none',
'MozUserSelect': 'none'
})
.on('selectstart', false)
.on('mousedown', false);
这其实很简单。 要禁用文本选择(也可以点击+拖动文本(例如Chrome中的链接)),只需使用以下jQuery代码:
$('body, html').mousedown(function(event) {
event.preventDefault();
});
这一切都是为了防止在主体和html标记中单击鼠标(mousedown())时发生默认情况。你可以很容易地通过改变两个引号之间的文本来改变元素(例如改变$('body, html')到$('#myUnselectableDiv'),使myUnselectableDiv成为,好吧,不可选择的div。
一个简短的片段向你展示/证明这一点:
$ (' # no-select ') .mousedown(函数(事件){ event.preventDefault (); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <span id="no-select">我打赌你不能选择这个文本,或拖动<a href="#">这个链接</a>, </span> <br/><span>但是你可以选择这个文本,并拖动<a href="#">this link</a>!< / span >
请注意,这个效果不是完美的,并且在整个窗口不可选的情况下表现最好。你可能还想补充
取消一些热键(如Ctrl+a和Ctrl+c)。测试:Cmd+a和Cmd+c
也可以用上面弗拉基米尔的回答。(点击这里查看他的职位)
我认为这段代码可以在所有浏览器上运行,所需的开销最少。它实际上是上述所有答案的混合体。如果你发现了窃听器,请告诉我!
添加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();