我制作了一个简单的图像裁剪器,您可以将绿色框(要裁剪的区域)移到红色框(原始图像)上。在这里:
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
隐藏它,但这会使框不可拖动。有什么方法可以隐藏这个淡绿色框,同时仍然能够拖动裁剪区域吗?
最佳答案
可能有一种方法可以调整您对拖动事件的处理以实现该结果,但我无法让它发挥作用。这里有一些关于相同的事情,但使用 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>
关于javascript - 如何隐藏指针事件但仍然能够启动拖动事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269409/