如何隐藏指针事件,但仍能启动拖动事件



我做了一个简单的图像裁剪器,您可以在其中将绿色框(要裁剪的区域)移动到红色框(原始图像)上。在这里:

var crop = document.querySelector(".image .crop");
crop.addEventListener("drag", function() {
  var mouseoffset = [event.clientX, event.clientY];
  crop.style.left = mouseoffset[0] + "px";
  crop.style.top = mouseoffset[1] + "px";
});
crop.addEventListener("dragend", function() {
  var mouseoffset = [event.clientX, event.clientY];
  crop.style.left = mouseoffset[0] + "px";
  crop.style.top = mouseoffset[1] + "px";
});
.image {
  position:   relative;
  width:      400px;
  height:     400px;
  overflow:   hidden;
  background: #C00;
}
.image .crop {
  position:   absolute;
  width:      150px;
  height:     150px;
  background: rgba(64,168,36,1);
}
<div class="image">
  <div class="crop" draggable="true"></div>
</div>

但是有一个问题:拖动时您会注意到一个淡绿色的框。我可以用pointer-events: none隐藏它,但这会使该框无法拖动。有什么方法可以隐藏这个淡绿色框,同时仍然能够拖动裁剪区域?

可能有一种方法可以调整拖动事件以达到该结果,但我无法让它工作。这是关于同样的事情,但与mousedownmouseupmousemove

var crop = document.querySelector(".image .crop");
crop.addEventListener("mousedown", function(event) {
  document.onmousemove = function(event) {
    moveBox(event);
  };
  document.onmouseup = function(event) {
    stopMoving(event);
  }
});
function moveBox(event) {
  event.preventDefault();
  var mouseoffset = [event.clientX, event.clientY];
  crop.style.left = mouseoffset[0] + "px";
  crop.style.top = mouseoffset[1] + "px";
}
function stopMoving(event) {
  document.onmousemove = null;
  document.onmouseup = null;
}
.image {
  position: relative;
  width: 400px;
  height: 400px;
  overflow: hidden;
  background: #C00;
}
.image .crop {
  position: absolute;
  width: 150px;
  height: 150px;
  background: rgba(64, 168, 36, 1);
}
<div class="image">
  <div class="crop" draggable="true"></div>
</div>

最新更新