Javascript 如何使用jQuery检测单击而不是拖动?
我有一些代码可以在用户单击Javascript 如何使用jQuery检测单击而不是拖动?,javascript,jquery,mouseevent,jquery-events,Javascript,Jquery,Mouseevent,Jquery Events,我有一些代码可以在用户单击p标记时选择文本,但我不想在用户选择其中的文本时这样做。是否可以检测单击但不拖动 我有如下简单代码: $('.conteiner').on('click', 'p.xxx', function() { $(this).selection(); }); 但即使我在mousedown和mouseup之间拖动鼠标,也会执行click。选择是使用getSelection或Range选择文本的插件。与此类似: 您可以使用mousedown和mouseup来检测是否存在阻力
p
标记时选择文本,但我不想在用户选择其中的文本时这样做。是否可以检测单击但不拖动
我有如下简单代码:
$('.conteiner').on('click', 'p.xxx', function() {
$(this).selection();
});
但即使我在mousedown和mouseup之间拖动鼠标,也会执行click。选择是使用getSelection或Range选择文本的插件。与此类似:
您可以使用mousedown和mouseup来检测是否存在阻力
$(function() {
var isDragging = false;
$(".conteiner")
.mousedown(function() {
$(window).mousemove(function() {
isDragging = true;
$(window).unbind("mousemove");
});
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
if (!wasDragging) {
$(this).selection();
}
});
});
以下是plunker演示:
找到了更好的方法,因为我需要检测拖动来选择文本,这样效果更好:
var get_selected_text = (function() {
if (window.getSelection || document.getSelection) {
return function() {
var selection = (window.getSelection || document.getSelection)();
if (selection.text) {
return selection.text;
} else {
return selection.toString();
}
};
} else if (document.selection && document.selection.type !== "Control") {
return function() {
return document.selection.createRange().text;
};
}
return function() {
return '';
};
})();
self.mouseup(function() {
if (get_selected_text() === '') {
// click not drag
}
});
高级模式下闭包编译器OP解决方案的类型注释版本
const get_selected_text = (/** @return {function():string} */ function() {
if (window.getSelection || document.getSelection) {
return function () {
const selection = /** @type {function():Object<string,?>} */ (window.getSelection || document.getSelection)();
if (typeof selection['text'] === "string") {
return selection['text'];
} else {
return selection.toString();
}
};
} else if (document.selection && document.selection.type !== "Control") {
return function () {
return document.selection.createRange().text;
};
}
return function () {
return '';
};
})();
const get_selected_text=(/**@return{function():string}*/function(){
if(window.getSelection | | document.getSelection){
返回函数(){
const selection=/**@type{function():Object}*/(window.getSelection | | document.getSelection)();
如果(选择的类型['text']=“string”){
返回选择['text'];
}否则{
返回selection.toString();
}
};
}else if(document.selection&&document.selection.type!=“控制”){
返回函数(){
return document.selection.createRange().text;
};
}
返回函数(){
返回“”;
};
})();
我已经为此(自定义事件)创建了一个插件