<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>拖放实例</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#div1{
width: 400px;
height: 400px;
margin: 5px auto 0;
border: 1px solid #cccccc;
display: flex;
justify-content: center;
align-items: center;
}
img{
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<!--定义放置区域-->
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<br/>
<!--定义可拖放元素-->
<img src="img/picture5.png" alt="#" id="drag1" draggable="true" ondragstart="drags(event)"/>
<script type="text/javascript">
//1、定义可拖放对象
//2、定义拖放元素
function drags(ev){
ev.dataTransfer.setData('text',ev.target.id);
}
//3、定义可放置区
function allowDrop(ev){
ev.preventDefault();
}
//4、进行放置
function drop(ev){
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
ev.target.appendChild(document.getElementById(data));
}
</script>
</body>
</html>
网友评论