当双击 html 页面时,大多数浏览器会选择您双击的单词(或您三次单击的段落)。有没有办法摆脱这种行为?
请注意,我不想通过单击+拖动禁用常规选择;即 jQuery UI 的 $('body').disableSelection()
和 document.onselectstart
DOM 事件不是我想要的。
最佳答案
我担心您无法阻止选择本身成为浏览器的“ native 行为”,但您可以在做出选择后立即清除选择:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
编辑:为了防止通过“三次点击”选择整个段落,这里是所需的代码:
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();
}
应该是跨浏览器的,请报告任何无法正常工作的浏览器。
关于JavaScript:通过双击禁用文本选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117466/