我希望能够使用jquery绑定多个顺序事件.我想做以下事情:
点击
div1- 也就是mousedown事件 - 现在,如果您在STILL按下鼠标时开始移动鼠标,那么执行某些功能.
这样做最顺畅的方法是什么?只是为了把一个if一个的内部.on()通话,或者是有什么简单?
var $div = $("div");
var mousemove = function() { ... };
$div.on({
mousedown: function() {
$div.on("mousemove", mousemove);
},
mouseup: function() {
$div.off("mousemove", mousemove);
}
});?
Run Code Online (Sandbox Code Playgroud)
请注意,.on()并.off()要结合并分别取消绑定事件所建议的方法.
或者,您可以将mouseup事件绑定到document.这样,即使在悬停元素时未发生鼠标,也可以检测到鼠标的释放.
var $document = $(document);
var $div = $("div");
var mousemove = function() { ... };
$div.mousedown(function() {
$div.on("mousemove", mousemove);
})
$document.mouseup(function() {
$div.off("mousemove", mousemove);
});?
Run Code Online (Sandbox Code Playgroud)
此外,它的简写功能.我们称之为.drag().
$.fn.drag = function(fn) {
var $document = $(document);
return $(this).each(function() {
var self = this;
var $this = $(this);
var mousemove = function() {
fn.dragging && fn.dragging.call($this);
};
$this.mousedown(function() {
fn.start && fn.start.call($this);
fn.dragging && $this.on("mousemove", mousemove);
});
$document.mouseup(function() {
fn.dragging && $this.off("mousemove", mousemove);
fn.stop && fn.stop.call(self);
});
});
};
Run Code Online (Sandbox Code Playgroud)
$("div").drag({
start: function() { ... },
dragging: function() { ... },
stop: function() { ... }
});?
Run Code Online (Sandbox Code Playgroud)