Created
May 15, 2018 16:41
-
-
Save Jancat/7e0ff71c2469cfbc04a135a1dbf78f1e to your computer and use it in GitHub Desktop.
H5 Simple Drag
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="dropzone"> | |
<div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)"> | |
This div is draggable | |
</div> | |
</div> | |
<div class="dropzone"></div> | |
<div class="dropzone"></div> | |
<div class="dropzone"></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
var dragged | |
/* 拖动目标元素时触发drag事件 */ | |
document.addEventListener('drag', function(event) {}, false) | |
document.addEventListener( | |
'dragstart', | |
function(event) { | |
// 保存拖动元素的引用(ref.) | |
dragged = event.target | |
// 使其半透明 | |
event.target.style.opacity = 0.5 | |
event.dataTransfer.effectAllowed = 'move' | |
}, | |
false, | |
) | |
document.addEventListener( | |
'dragend', | |
function(event) { | |
// 重置透明度 | |
event.target.style.opacity = '' | |
}, | |
false, | |
) | |
/* 放置目标元素时触发事件 */ | |
document.addEventListener( | |
'dragover', | |
function(event) { | |
// 阻止默认动作以启用drop | |
event.preventDefault() | |
}, | |
false, | |
) | |
document.addEventListener( | |
'dragenter', | |
function(event) { | |
// 当可拖动的元素进入可放置的目标时高亮目标节点 | |
if (event.target.className == 'dropzone') { | |
event.target.style.background = 'purple' | |
} | |
}, | |
false, | |
) | |
document.addEventListener( | |
'dragleave', | |
function(event) { | |
// 当拖动元素离开可放置目标节点,重置其背景 | |
if (event.target.className == 'dropzone') { | |
event.target.style.background = '' | |
} | |
}, | |
false, | |
) | |
document.addEventListener( | |
'drop', | |
function(event) { | |
// 阻止默认动作(如打开一些元素的链接) | |
event.preventDefault() | |
// 将拖动的元素到所选择的放置目标节点中 | |
if (event.target.className == 'dropzone') { | |
event.target.style.background = '' | |
dragged.parentNode.removeChild(dragged) | |
event.target.appendChild(dragged) | |
} | |
}, | |
false, | |
) |
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
#draggable { | |
width: 200px; | |
height: 20px; | |
text-align: center; | |
background: white; | |
cursor: move; | |
} | |
.dropzone { | |
width: 200px; | |
height: 20px; | |
background: blueviolet; | |
margin-bottom: 10px; | |
padding: 10px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment