我做了一个简单的图像裁剪器,在其中将绿色框(要裁剪的区域)移到红色框(原始图像)上。在这里:
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
隐藏它,但这会使该框变得无法拖动。有什么办法可以隐藏这个浅绿色的框,同时仍然可以拖动裁剪区域?
答案 0 :(得分:1)
也许有一种方法可以通过拖动事件来适应您所发生的事情,以实现该结果,但是我无法使其工作。除了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>