Javascript 如何使用 jQuery 禁用文本选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2700000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable text selection using jQuery?
提问by Dawid Ohia
Does jQuery or jQuery-UI have any functionality to disable text selection for given document elements?
jQuery 或 jQuery-UI 是否具有禁用给定文档元素的文本选择的功能?
回答by SLaks
In jQuery 1.8, this can be done as follows:
在 jQuery 1.8 中,这可以按如下方式完成:
(function($){
$.fn.disableSelection = function() {
return this
.attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
};
})(jQuery);
回答by Damien
If you use jQuery UI, there is a method for that, but it can only handle mouse selection (i.e. CTRL+Ais still working):
如果你使用 jQuery UI,有一个方法,但它只能处理鼠标选择(即CTRL+A仍然有效):
$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9
The code is realy simple, if you don't want to use jQuery UI :
代码非常简单,如果您不想使用 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; });
回答by Plynx
I found this answer ( Prevent Highlight of Text Table) most helpful, and perhaps it can be combined with another way of providing IE compatibility.
我发现这个答案(防止文本表突出显示)最有帮助,也许它可以与提供 IE 兼容性的另一种方式结合使用。
#yourTable
{
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
}
回答by Vladimir
Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+aand Ctrl+c. Test:Cmd+aand Cmd+c)
这里有一个更全面的解决断开选择,取消一些热键(如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);
and call example:
并调用示例:
$(':not(input,select,textarea)').disableSelection();
This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:
对于旧版本的 FireFox(我不知道是哪个),这也可能不够。如果所有这些都不起作用,请添加以下内容:
.on('mousedown', false)
回答by Arvid Vermote
The following would disable the selection of all classes 'item' in all common browsers (IE, Chrome, Mozilla, Opera and Safari):
以下将禁用所有常见浏览器(IE、Chrome、Mozilla、Opera 和 Safari)中所有类“item”的选择:
$(".item")
.attr('unselectable', 'on')
.css({
'user-select': 'none',
'MozUserSelect': 'none'
})
.on('selectstart', false)
.on('mousedown', false);
回答by deerhunter
$(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");
});
回答by Code Spy
This can easily be done using JavaScript This is applicable to all Browsers
这可以使用 JavaScript 轻松完成这适用于所有浏览器
<script type="text/javascript">
/***********************************************
* Disable Text Selection script- ? Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
target.style.MozUserSelect="none"
else //All other route (For Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
</script>
Call to this function
调用这个函数
<script type="text/javascript">
disableSelection(document.body)
</script>
回答by Zach Barham
This is actually very simple. To disable text selection (and also click+drag-ing text (e.g a link in Chrome)), just use the following jQuery code:
这其实很简单。要禁用文本选择(以及单击+拖动文本(例如 Chrome 中的链接)),只需使用以下 jQuery 代码:
$('body, html').mousedown(function(event) {
event.preventDefault();
});
All this does is prevent the default from happening when you click with your mouse (mousedown()) in the bodyand htmltags. You can very easily change the element just by changing the text in-between the two quotes (e.g change $('body, html')to $('#myUnselectableDiv')to make the myUnselectableDivdiv to be, well, unselectable.
所有这一切都是为了防止在您用鼠标 ( mousedown()) 在body和html标签中单击时发生默认情况。你可以很容易只是通过改变文本之间的两个引号(如改变而改变的元素$('body, html'),以$('#myUnselectableDiv')使myUnselectableDivDIV是,好了,不可选。
A quick snippet to show/prove this to you:
向您展示/证明这一点的快速片段:
$('#no-select').mousedown(function(event) {
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
Please note that this effect is not perfect, and performs the best while making the whole window not selectable. You might also want to add
请注意,此效果并不完美,在使整个窗口不可选的情况下效果最佳。您可能还想添加
the cancellation of some of the hot keys (such as Ctrl+aand Ctrl+c. Test:Cmd+aand Cmd+c)
取消一些热键(例如Ctrl+a和Ctrl+c。测试:Cmd+a和Cmd+c)
as well, by using that section of Vladimir's answer above. (get to his post here)
同样,通过使用上面弗拉基米尔回答的那部分。(到他的帖子这里)
回答by Dave
I've tried all the approaches, and this one is the simplest for me because I'm using IWebBrowser2 and don't have 10 browsers to contend with:
我已经尝试了所有的方法,这个对我来说是最简单的,因为我使用的是 IWebBrowser2 并且没有 10 个浏览器需要处理:
document.onselectstart = new Function('return false;');
Works perfectly for me!
非常适合我!
回答by user1415855
1 line solution for CHROME:
CHROME 的 1 行解决方案:
body.style.webkitUserSelect = "none";
and FF:
和FF:
body.style.MozUserSelect = "none";
IE requires setting the "unselectable" attribute (details on bottom).
IE 需要设置“unselectable”属性(详情见底部)。
I tested this in Chrome and it works. This property is inherited so setting it on the body element will disable selection in your entire document.
我在 Chrome 中对此进行了测试,并且可以正常工作。此属性是继承的,因此在 body 元素上设置它会禁用整个文档中的选择。
Details here: http://help.dottoro.com/ljrlukea.php
详情请见:http: //help.dottoro.com/ljrlukea.php
If you're using Closure, just call this function:
如果您正在使用 Closure,只需调用此函数:
goog.style.setUnselectable(myElement, true);
It handles all browsers transparently.
它透明地处理所有浏览器。
The non-IE browsers are handled like this:
非 IE 浏览器是这样处理的:
goog.style.unselectableStyle_ =
goog.userAgent.GECKO ? 'MozUserSelect' :
goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
null;
Defined here: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html
此处定义:http: //closure-library.googlecode.com/svn/!svn/ bc/4/trunk/closure/ goog/docs/ closure_goog_style_style.js.source.html
The IE portion is handled like this:
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);
}
}

