废话不多说直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5拖放API</title>
<style>
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
height: 100%;
}
.target{
width: 100px;
height: 100px;
background-color: #42b983;
text-align: center;
line-height: 100px;
}
.box{
width: 200px;
height: 200px;
background-color: #ffccaa;
padding: 20px;
box-sizing: border-box;
border: 1px solid #000;
margin: auto;
}
</style>
</head>
<body>
<!--被拖动元素-->
<div class="target" draggable="true" >
你拖我呀
</div>
<!--盒子元素-->
<div class="box"></div>
</body>
<script>
/*
常用拖放API:
1.作用在被拖放元素上的API:
ondragstart【开始拖动时触发】
ondrag【拖动过程中触发】
ondragend【释放鼠标,停止拖动时触发】
2.作用在盒子元素上的API:
ondragenter【有拖动对象进入范围时触发】
ondragover【拖动对象在盒子上时不断触发】(如果想要ondrop被触发,记得在此阻止默认事件)
ondragleave【拖动对象离开范围时触发】
ondrop【在范围内释放鼠标按键时触发】
*/
let target=document.querySelector('.target')
target.ondragstart=function (){
console.log("开始托动");
}
// target.οndrag=function (){
// console.log("正在拖动中")
// }
target.ondragend=function (){
console.log("停止拖动")
}
let box=document.querySelector('.box')
box.ondragenter=function (){
console.log("有拖动元素进入")
}
box.ondragover=function (){
console.log("有拖动元素在我上方活动")
}
box.ondragleave=function (){
console.log("有拖动元素离开我范围")
}
box.ondrop=function (){
console.log("有拖动元素在我上方停止了拖动")
}
</script>
</html>