javascript 如何通过 jQuery 禁用文本选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7675450/
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 via jQuery?
提问by Dennis
I know this question have been already asked (here), but all the answers I've found dealt with css selector :selection (that is not yet too widely supported by browsers).
我知道已经有人问过这个问题(这里),但我找到的所有答案都涉及 css 选择器 :selection (浏览器还没有广泛支持)。
So, how can I disable text selection on my html page via jQuery, not relying on css tricks?
那么,如何通过 jQuery 在我的 html 页面上禁用文本选择,而不依赖于 css 技巧?
采纳答案by Merianos Nikos
回答by Halfhoot
Here is a simple one-liner to disable selecting text on your whole page. (whether you should or not is another question)
这是一个简单的单行代码,用于禁用在整个页面上选择文本。(该不该是另一个问题)
$(document).bind('selectstart dragstart', function(e) {
e.preventDefault();
return false;
});
回答by Dennis
If you want to avoid plugins, you can extract the relevant parts from the jQuery UI source:
如果你想避免插件,你可以从 jQuery UI 源中提取相关部分:
/*!
* jQuery UI 1.8.16
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI
*/
$.support.selectstart = "onselectstart" in document.createElement("div");
$.fn.disableSelection = function() {
return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
".ui-disableSelection", function( event ) {
event.preventDefault();
});
};
$("#somediv").disableSelection();
回答by ThiefMaster
Include jQuery UI and use $(element).disableSelection()
.
包括 jQuery UI 并使用$(element).disableSelection()
.
However, disabling text selection is veryuser-unfriendly unless used in a context where accidental selections are likely (e.g. Drag&Drop or buttons where users are likely to doubleclick to perform multiple changes faster (e.g. in spinners))
但是,禁用文本选择对用户非常不友好,除非在可能发生意外选择的上下文中使用(例如拖放或用户可能双击以更快地执行多个更改的按钮(例如在微调器中))