在 MooTools 中是否可以使用 mousedown
、mouseup
和 mousemove
事件来定义拖动事件。我希望能够执行以下操作:
$('#knob').addEvent('drag', function (e) {
// Drag event code goes here...
});
最佳答案
Dragging
虽然 Mootools 已经实现了所有你需要的 drag, drop, slide and similar effects , 编写您自己的事件是了解事件如何工作的好方法。以下是如何使用 Element.Events Object 添加其他自定义事件的示例。 .
效果从注册 mousemove 事件的 mousedown 事件开始。当拖动结束时,将触发 mouseup 事件以移除 mousemove 事件监听器。
由于鼠标可能会离开框(不会触发 mouseup 进行清理),因此还添加了 mouseout 事件。
在效果的每一步,drag
事件处理程序都会启动,原始事件对象作为参数传递,您可以通过 console.log( e.输入 );
window.addEvent( 'domready', function() {;
Element.Events.drag = {
// the function that will get fired when the custom event is added
onAdd: function() {
this.addEvents({
mousedown: function(e) {
this.store( 'x', e.page.x - this.getPosition().x );
this.store( 'y', e.page.y - this.getPosition().y );
this.addEvents({
mousemove: function(e) {
this.setPosition({
x: e.page.x - this.retrieve( 'x' ),
y: e.page.y - this.retrieve( 'y' )
});
this.fireEvent( 'drag', e );
},
mouseout: function(e) {
this.fireEvent( 'mouseup', e );
}
});
},
mouseup: function(e) {
this.removeEvents( 'mousemove' );
this.removeEvents( 'mouseout' );
this.fireEvent( 'drag', e );
}
});
},
// the function that will get fired when the custom event is removed
onRemove: function() {
this.removeEvents( 'mousedown' );
this.removeEvents( 'mouseup' );
}
};
$('draggable').addEvent( 'drag', function( e ) {
console.log( e.type );
});
// $('draggable').removeEvents( 'drag' );
});
一些关于 Mootools 事件的好文章:
关于javascript - MooTools 自定义拖动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649335/