JavaScript:通过双击禁用文本选择 [英] JavaScript: Disable text selection via doubleclick
问题描述
双击html页面时,大多数浏览器都会选择您双击的单词(或者您双击的段落)。有没有办法摆脱这种行为?
When double-clicking on a html page most browsers select the word you double-click on (or the paragraph you triple-click on). Is there a way to get rid of this behavior?
请注意,我不想通过单击+拖动禁用常规选择;即jQuery UI的 $('body')。disableSelection()
和 document.onselectstart
DOM事件不是我
Note that I do not want to disable regular selection via single-click+dragging; i.e. jQuery UI's $('body').disableSelection()
and the document.onselectstart
DOM event are not what I want.
推荐答案
我担心您无法阻止选择本身成为浏览器的原生行为,但您可以清除选择权后:
I fear you can't prevent the selection itself being "native behavior" of the browser, but you can clear the selection right after it's made:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
编辑:也可以防止通过三重点击选择整个段落,这里是所需的代码:
Edit: to also prevent selecting whole paragraph by "triple click", here is the required code:
var _tripleClickTimer = 0;
var _mouseDown = false;
document.onmousedown = function() {
_mouseDown = true;
};
document.onmouseup = function() {
_mouseDown = false;
};
document.ondblclick = function DoubleClick(evt) {
ClearSelection();
window.clearTimeout(_tripleClickTimer);
//handle triple click selecting whole paragraph
document.onclick = function() {
ClearSelection();
};
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
};
function RemoveDocumentClick() {
if (!_mouseDown) {
document.onclick = null;
return true;
}
_tripleClickTimer = window.setTimeout(RemoveDocumentClick, 1000);
return false;
}
function ClearSelection() {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
应该跨浏览器,请报告任何浏览器不工作的地方。
Should be cross browser, please report any browser where it's not working.
这篇关于JavaScript:通过双击禁用文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!