原生javaScript實現拖拽功能
阿新 • • 發佈:2018-12-01
<head>
<meta charset="utf-8">
<title>拖拽效果</title>
<style type="text/css">
.drag_main{
width:50px;
height:50px;
position: absolute;
top:10px;
left:10px;
}
.drag_main img{
width :50px;
height:50px;
}
</style>
</head>
<body>
<div class="drag_main" id="dragImg" draggable="true"><img src="dargImg.png"></div>
</body>
<script type="text/javascript">
//原生js實現
//querySelector() 匹配指定 CSS 選擇器的一個元素。
var dragImg = document.querySelector("#dragImg" );
var x,y;
dragImg.addEventListener('dragstart', (e) =>{
console.log("start e",e);
//dataTransfer儲存拖拽到瀏覽器的資料
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text",'');
x = e.offsetX || e.layerX;
y = e.offsetY || e.layerY;
return true;
},false)
document.addEventListener('dragover', (e) =>{
//取消事件的預設動作和停止事件的傳播
e.preventDefault() || e.stopPropagation();
},false)
document.addEventListener('drop', (e) =>{
console.log("drop e",e);
dragImg.style.left = (e.pageX - x) + 'px';
dragImg.style.top = (e.pageY - y) + 'px';
e.preventDefault() || e.stopPropagation();
},false)
</script>