首页投稿(暂停使用,暂停投稿)web前端

ondragstart 添加ghost image 在拖拽 问题

2017-07-06  本文已影响0人  北纬40度的思念

当我们想要在拖拽时添加自定义的ghost image的时候,我们可以用event.dataTransfer.setDragImage(element,x,y)来实现这个效果。

接下来我们顺着这个方法往下走:

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8"> 
  <title>拖拽demo</title>
  <style type="text/css">
    #div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
  </style>
</head>
<body>
  <p>拖动图片到矩形框中:</p>
  <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  ![](https://img.haomeiwen.com/i4910610/39e145aaa136179f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</body>
</html>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function dragstart(ev) {
  ev.dataTransfer.setData("Text",ev.target.id);
  var ghost = document.createElement("div");
  ghost.id = 'GHOST_LABEL';
  ghost.style.backgroundColor = "#b8b8b8";
  ghost.style.color = "#414141";
  ghost.style.padding = "0 10px 0 15px";
  ghost.style.lineHeight = "24px";
  ghost.innerHTML = "this is a image!";
  ghost.style.display = "inline";
  document.body.appendChild(ghost);
  ev.dataTransfer.setDragImage(ghost, 0, 0);
}

function drop(ev) {
  ev.preventDefault();
  var data=ev.dataTransfer.getData("Text");
  ev.target.appendChild(document.getElementById(data));
}
</script>

这个时候我们设置好了,但是会不断多出一个元素来。这个时候我们将添加的元素移出到可是范围,并做好内存回收。你可以在ondragend的时候去把添加的元素删除掉。

function dragstart(ev) {
  ev.dataTransfer.setData("Text",ev.target.id);
  var ghost = document.createElement("div");
  ghost.id = 'GHOST_LABEL';
  ghost.style.backgroundColor = "#b8b8b8";
  ghost.style.color = "#414141";
  ghost.style.padding = "0 10px 0 15px";
  ghost.style.lineHeight = "24px";
  ghost.innerHTML = "this is a image!";
  ghost.style.display = "inline";
  ghost.style.position = "absolute";
  ghost.style.left = "-2000px";
  ghost.style.top = "0px";
  document.body.appendChild(ghost);
  ev.dataTransfer.setDragImage(ghost, 0, 0);
}

function dragend(ev) {
 document.body.removeChild(document.getElementById('GHOST_LABEL'))
}

到此我们就把效果做好了。如果不执行 document.body.appendChild(ghost)这一句,会出现拖拽不一定有效果或直接没有想要的效果。

上一篇 下一篇

猜你喜欢

热点阅读