js实现拖放

<!DOCTYPE html>
<html>
<head>
<title>a元素拖到b元素里b元素就成了a元素的父元素 </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no" />
<meta name="format-detection"content="telephone=no"/>-->
<style>
#div{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #ff0000;
margin: 40px auto 0 auto;
line-height: 100px;
text-align: center;
color: #fff0df;
}
#container{
display: flex;
}
#container>div{
height: 200px;
width: 200px;
flex:1;
border: 1px solid #000000;
padding-top: 20px;
text-align: center;
}
</style>
</head>
<body>
<div id="container">
<div>yellow</div>
<div>green</div>
<div>blue</div>
<div>black</div>
</div>
<div draggable="true" id="div"></div>
<script>
const [div,conatiner]=[
document.getElementById('div'),
document.getElementById('container')
];
div.ondragstart=function(e){
div.innerHTML='dragstart';
conatiner.style.backgroundColor='rgba(255,0,0,.1)';
e.dataTransfer.setData('id','div');
}
div.ondrag=function(e){
div.innerHTML='dragging';
}
div.ondragend=function(e){
div.innerHTML='dragend';
conatiner.style.backgroundColor='rgba(255,0,0,0)';
}
conatiner.ondragenter=function(e){
e.preventDefault();
e.target.style.backgroundColor='rgba(255,0,0,.3)';
//drop之前没有获取不到data对象
div.style.backgroundColor= e.target.innerHTML;
}
conatiner.ondragleave=function(e){
e.preventDefault();
e.target.style.backgroundColor='rgba(255,0,0,0)';
}
//目标对象容许被拖拽元素拖拽进来 默认不容许
conatiner.ondragover=function(e){
e.preventDefault();
}
//目标对象接受被拖拽元素放下
conatiner.ondrop=function(e){
const target=e.target;
const id=e.dataTransfer.getData('id');
const div=document.getElementById(id);
div.style.backgroundColor=target.innerHTML;
target.appendChild(div);
}
</script>
</body>
</html>

posted @ 2020-03-05 15:20  技术研究与问题解决  阅读(120)  评论(0编辑  收藏  举报