代码之家  ›  专栏  ›  技术社区  ›  Wais Kamal

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

  •  0
  • Wais Kamal  · 技术社区  · 6 年前

    我制作了一个简单的图像裁剪器,将绿色框(要裁剪的区域)移动到红色框(原始图像)上。这里是:

    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 ,但这会使框不可折叠。有没有什么方法可以隐藏这个淡绿色的盒子,同时还能拖动作物区?

    1 回复  |  直到 6 年前
        1
  •  1
  •   GenericUser    6 年前

    可能有一种方法可以调整拖动事件的情况,以实现该结果,但我无法使其工作。这是同样的事情,但是 mousedown , mouseup mousemove .

    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>