练习1 效果:实现当拖拽结束时小方块停在鼠标松开的位置
<!-- HTML5 拖拽 -->
<div class="a" draggable="true"></div>
//draggabl是拖拽属性,为true时可拖拽,为flase时不可拖拽
//本身默认draggable为true的标签有<a> <img>;
<script>
var oDragDiv = document.getElementsByClassName('a')[0];
var beginX = 0;
var beginY = 0;
//开始事件:按下物体的一瞬间是不会触发事件的
// 当物体开始移动时触发
oDragDiv.ondragstart = function(e){
beginX = e.clientX;
beginY = e.clientY;
// console.log(e);
}
//移动事件:在拖拽的时触发
// oDragDiv.ondrag = function(e){
// console.log(e);
// }
// 结束事件:当停止拖拽鼠标松开时触发
oDragDiv.ondragend = function(e){
//实现当拖拽结束时小方块停在鼠标松开的位置
var x = e.clientX - beginX;
var y = e.clientY - beginY;
oDragDiv.style.left = oDragDiv.offsetLeft + x + "px";
oDragDiv.style.top = oDragDiv.offsetTop + y + "px";
console.log(oDragDiv.style.left);
console.log(oDragDiv.style.top);
//console.log(e);
}
</script>
div的CSS样式
.a{
width: 100px;
height: 100px;
background-color: #ffebcd;
cursor: pointer;
position: absolute;
}
练习2 效果 把小方块拖入指定的区域并把其撑开
<!-- HTML5 拖拽 -->
<div class="box1">
box1
<div class="a" draggable="true"></div>
</div>
<div class="box2">box2</div>
<script>
var oDragDiv = document.getElementsByClassName('a')[0];
var drag;
//开始事件:按下物体的一瞬间是不会触发事件的
// 当物体开始移动时触发
oDragDiv.ondragstart = function(e){
drag = e.target;
// console.log(drag);
}
var box2 = document.getElementsByClassName('box2')[0];
box2.ondragover = function(e){
e.preventDefault();
}
box2.ondrop = function(e){
console.log(drag);
box2.appendChild(drag);
drag = null;
}
</script>
相应的css样式
.box1,.box2{
border: 1px solid #000000;
display: inline-block;
padding: 10px;
margin: 60px;
}
.a{
width: 100px;
height: 100px;
background-color: #ffebcd;
cursor: pointer;
/* position: absolute; */
}