如何使用 Javascript 或 jQuery 取消选择文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8684751/
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 can I deselect text using Javascript or jQuery?
提问by Leo Jiang
I have a draggable (jQuery UI) element with "canceled" text on it. Here's what I mean:
我有一个带有“已取消”文本的可拖动(jQuery UI)元素。这就是我的意思:
$('#main').draggable({
cancel: '#main>* *',
start: function(){
// deselect text
}
});
When I drag the element, I often select the text by accident. I want to deselect the text when the element is dragged.
当我拖动元素时,我经常不小心选择了文本。我想在拖动元素时取消选择文本。
采纳答案by Emmanuel N
Clear document selection document.selection.empty();
清除文档选择 document.selection.empty();
Something like:
就像是:
$('#main').draggable({
cancel: '#main>* *',
start: function(){
// deselect text
document.selection.empty();
}
});
回答by Eric G
To deselect everything you can use:
要取消选择您可以使用的所有内容:
document.getSelection().removeAllRanges();
回答by exafred
jQuery UI now includes .disableSelection()
, which you can use to prevent the text inside your elements from being selected. The API documentation on it isn't hugely useful, but: http://api.jqueryui.com/disableSelection/
jQuery UI 现在包含.disableSelection()
,您可以使用它来防止元素内的文本被选中。关于它的 API 文档不是很有用,但是:http: //api.jqueryui.com/disableSelection/
As an aside, Eric G's answer proved supremely helpful for me when creating my own "text highlighting" tool - as Lawrence remarked, it won't throw out an error if no text has been selected.
顺便说一句,在创建我自己的“文本突出显示”工具时,Eric G 的回答证明对我非常有帮助 - 正如 Lawrence 所说,如果没有选择任何文本,它不会抛出错误。