1. 元素跟随鼠标
document.addEventListener('mousemove', function(event) {
var myDiv = document.getElementById('myDiv')
myDiv.style.left = event.clientX + 'px'
myDiv.style.top = event.clientY + 'px'
})
2. 可拖动元素的事件
var DragDrop = function () { var dragdrop = new EventTarget() var dragging = null var diffX = 0 var diffY = 0 function handleEvent(event) { var target = event.target switch(event.type) { case 'mousedown': if (target.className.indexOf('draggble') > -1) { dragging = target diffX = event.clientX - target.offsetLeft diffY = event.clientY - target.offsetTop dragdrop.fire({type: 'dragstart', target: dragging, x: event.clientX, y: event.clientY}) } break case 'mousemove': if (dragging !== null) { dragging.style.left = (event.clientX - diffX) + 'px' dragging.style.top = (event.clientY - diffY) + 'px' dragdrop.fire({type: 'drag', target: dragging, x: event.clientX, y: event.clientY}) } break case 'mouseup': dragging = null dragdrop.fire({type: 'dragend', target: dragging, x: event.clientX, y: event.clientY}) break } } dragdrop.enable = function() { document.addEventListener('mousedown', handleEvent) document.addEventListener('mousemove', handleEvent) document.addEventListener('mouseup', handleEvent) } dragdrop.disable = function() { document.removeEventListener('mousedown', handleEvent) document.removeEventListener('mousemove', handleEvent) document.removeEventListener('mouseup', handleEvent) } return dragdrop } var dragdrop = DragDrop() dragdrop.addHandler('dragstart', function(event) { console.log('start', event) }) dragdrop.addHandler('drag', function(event) { console.log('drag', event) }) dragdrop.addHandler('dragend', function(event){ console.log('end', event) }) dragdrop.enable()
参考: EventTarget