更改HTML5拖放中的重影图像

change ghost image in HTML5 drag and drop

本文关键字:重影 图像 HTML5 拖放 更改      更新时间:2023-09-26

这里我有一些大的div,但它ghost对我来说太大了,我想更改它。这是我的解决方案:

<div draggable = "true" id = "ololo">
</div>
var k = document.getElementById("ololo");
k.addEventListener("dragstart", _drag, false);
function _drag(evt){
    var cl =  this.cloneNode(true);
    cl.style.backgroundColor = "blue";
    cl.style.width = "10px";
    cl.style.height = "10px";
    cl.style.position = "absolute";
    cl.style.left = "1000px";
    cl.style.overflow = "hidden";
    document.getElementsByTagName("body")[0].appendChild(cl);
    evt.dataTransfer.setDragImage(cl, 0, 0);
    window.setTimeout(function() {
       cl.parentNode.removeChild(cl);
    }, 1000);
}

Jsffidle演示它工作得很好,但在生产中使用它好吗?为什么当滚动条溢出时,我也隐藏了它?

使用z-index将克隆隐藏在原始可拖动对象后面,然后合并setTimeout()方法以稍后将其删除;防止DOM中不必要的重复。演示

这是分步指南的改进版本,位于kryogenix.org

JS、CSS、HTML

document.getElementById("drag-coveredup").addEventListener("dragstart", function(e) {
  var crt = this.cloneNode(true);
  crt.style.backgroundColor = "red";
  crt.style.height = "10px";
  crt.style.width = "10px";
  crt.style.position = "absolute";
  crt.style.top = "0";
  crt.style.left = "0";
  crt.style.zIndex = "-1";
  document.getElementById("drag-coveredup").appendChild(crt);
  e.dataTransfer.setDragImage(crt, 0, 0);
  window.setTimeout(function() {
    crt.parentNode.removeChild(crt);
  }, 1000);

}, false);
.dragdemo {
  width: 170px;
  height: 100px;
  position: relative;
  line-height: 100px;
  text-align: center;
  background: green;
  color: #efe;
}
<div id="drag-coveredup" class="dragdemo" draggable="true"></div>