Thi*_*ter 32 html javascript jquery selection
双击html页面时,大多数浏览器选择双击的单词(或三键单击的段落).有没有办法摆脱这种行为?
请注意,我不想通过单击+拖动禁用常规选择; 即jQuery UI $('body').disableSelection()和document.onselectstartDOM事件不是我想要的.
Sha*_*ard 38
我担心你无法阻止选择本身成为浏览器的"原生行为",但你可以在选择之后立即清除选择:
<script type="text/javascript">
document.ondblclick = function(evt) {
if (window.getSelection)
window.getSelection().removeAllRanges();
else if (document.selection)
document.selection.empty();
}
</script>
Run Code Online (Sandbox Code Playgroud)
编辑:也防止通过"三击"选择整个段落,这是必需的代码:
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();
}?
Run Code Online (Sandbox Code Playgroud)
应该是跨浏览器,请报告任何不起作用的浏览器.
把这个放在css感兴趣的部分
-moz-user-select : none;
-khtml-user-select : none;
-webkit-user-select : none;
-o-user-select : none;
user-select : none;
Run Code Online (Sandbox Code Playgroud)
以下适用于当前Chrome(v56),Firefox(v51)和MS Edge(v38)浏览器.
var test = document.getElementById('test');
test.addEventListener('mousedown', function(e){
if (e.detail > 1){
e.preventDefault();
}
});Run Code Online (Sandbox Code Playgroud)
<p id="test">This is a test area</p>Run Code Online (Sandbox Code Playgroud)
该MouseEvent.detail物业保持跟踪的当前点击计数可用于确定事件是否是双,特里普尔,或点击.
遗憾的是,Internet Explorer在超时期限后不会重置计数器,因此您不需要计算突发点击次数,而是计算自页面加载以来用户点击的次数.
如果您确实想在双击时禁用return false选择,而不仅仅是随后删除选择(对我来说看起来很难看),则需要在第二个 mousedown 事件中执行此操作(ondblclick 不起作用,因为选择是在 mousedown 上进行的)。
**如果有人根本不想选择,最好的解决方案是像 Maurizio Battaghini 提议的那样使用 CSS user-select : none;。
// set to true if you want to disable also the triple click event
// works in Chrome, always disabled in IE11
var disable_triple_click = true;
// set a global var to save the timestamp of the last mousedown
var down = new Date().getTime();
var old_down = down;
jQuery(document).ready(function($)
{
$('#demo').on('mousedown', function(e)
{
var time = new Date().getTime();
if((time - down) < 500 &&
(disable_triple_click || (down - old_down) > 500))
{
old_down = down;
down = time;
e.preventDefault(); // just in case
return false; // mandatory
}
old_down = down;
down = time;
});
});
Run Code Online (Sandbox Code Playgroud)
重要提示:我将灵敏度设置为 500 毫秒,但双击灵敏度(检测为双击的两次单击之间的最大时间)可能会因操作系统和浏览器的不同而异,并且通常可由用户配置。- api.jquery.com
在 Chrome 和 IE11 中测试。
| 归档时间: |
|
| 查看次数: |
24328 次 |
| 最近记录: |