Last active
May 19, 2018 07:04
-
-
Save Jancat/aa1c1b1af29dfa6a405afa4b9254d254 to your computer and use it in GitHub Desktop.
drag-drop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="square"></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 实现正方形的拖拽 | |
// 记录鼠标位置,赋予正方形position 属性 的 top 和 left | |
// 记录事件 mousedown mousemove mouseup | |
window.onload = function() { | |
const DragDrop = (function() { | |
let dragging = null // 记录拖拽的对象 | |
var diffX = 0 // 记录鼠标与正方形边缘的距离 | |
var diffY = 0 // 同上 | |
function dragEvent(event) { | |
var that = event.target | |
// 判断事件类型 | |
switch (event.type) { | |
// 记录鼠标点击处的位置,与目标的位置做差值 | |
case 'mousedown': | |
dragging = that | |
diffX = event.clientX - that.offsetLeft | |
diffY = event.clientY - that.offsetTop | |
break | |
// 实时修改正方形的position中的 top 和 left值 | |
case 'mousemove': | |
if (dragging !== null && event.clientX >= diffX && event.clientY >= diffY) { | |
dragging.style.left = event.clientX - diffX + 'px' | |
dragging.style.top = event.clientY - diffY + 'px' | |
} | |
break | |
// 将拖拽对象置为 null | |
case 'mouseup': | |
dragging = null | |
break | |
} | |
// ... do something | |
} | |
// 返回对象 | |
return { | |
// 触发,监听以上三个事件,监听对象document | |
fire: function() { | |
document.addEventListener('mousedown', dragEvent, false) | |
document.addEventListener('mousemove', dragEvent, false) | |
document.addEventListener('mouseup', dragEvent, false) | |
}, | |
} | |
})() | |
DragDrop.fire() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.square { | |
width: 100px; | |
height: 100px; | |
border: 1px solid #000; | |
background-color: #000; | |
position: absolute; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment