我尝试使用统一的方形图像制作一种拖放式拼图网站,并且我已经编写了拖动代码,以便通过<img>
元素拖动单个图像。
但是我注意到,将<img>
元素拖到附加了addEventListener("mousenter", function () {//code};)
的其他元素上时,mouseenter事件不会触发。如果我将鼠标移动到元素上而不拖动图像,则事件将正常触发。
有没有人对如何解决这个问题有任何想法?我唯一的猜测是<img>
元素阻止了监听器看到鼠标。
var dragImg = document.querySelector(".images img");
dragImg.addEventListener("mousedown", function () {
console.log("mousedown detected " + dragImg.clientHeight);
dragImg.setAttribute("id", "drag");
dragging = true;
});
dragImg.addEventListener("mousemove", function (event) {
if (dragging) {
dragImg.style.top = (event.clientY - dragImg.clientHeight/2) + "px";
dragImg.style.left = (event.clientX - dragImg.clientWidth/2) + "px";
}
});
dragImg.addEventListener("mouseup", function () {
console.log("mouseup detected");
dragging = false;
//reset position if not in clipboard
dragImg.removeAttribute("id");
dragImg.style.top = "";
dragImg.style.left = "";
});
//Clipboard behavior - This listener doesn't fire when dragging an img?
var clipboard = document.querySelector(".clipboard");
clipboard.addEventListener("mouseover", function () {
if (dragging) {
console.log("mouse entered clipboard!");
clipboard.style.backgroundColor = "red";
}
});
#drag {
position: absolute;
}
答案 0 :(得分:2)
问题是鼠标永远不会悬停.clipboard
,因为图像始终位于指针下方。
简单的解决方案添加pointer-events:none;
(旧浏览器不支持)。
var dragImg = document.querySelector(".images img");
var dragging = false;
dragImg.addEventListener("mousedown", function (event) {
event.stopPropagation();
console.log("mousedown detected " + dragImg.clientHeight);
dragImg.setAttribute("id", "drag");
dragging = true;
document.addEventListener('mousedown', function documentMouseDown(){
if (dragging) {
dragImg.removeAttribute("id");
dragging = false;
document.removeEventListener('mousedown', documentMouseDown);
}
});
});
document.addEventListener("mousemove", function (event) {
if (dragging) {
dragImg.style.top = (event.clientY - dragImg.clientHeight/2) + "px";
dragImg.style.left = (event.clientX - dragImg.clientWidth/2) + "px";
}
});
dragImg.addEventListener("mouseup", function () {
console.log("mouseup detected");
dragging = false;
//reset position if not in clipboard
dragImg.removeAttribute("id");
dragImg.style.top = "";
dragImg.style.left = "";
});
//Clipboard behavior - This listener doesn't fire when dragging an img?
var clipboard = document.querySelector(".clipboard");
clipboard.addEventListener("mouseover", function () {
if (dragging) {
console.log("mouse entered clipboard!");
clipboard.style.backgroundColor = "red";
}
});
&#13;
#drag {
position: absolute;
pointer-events:none;
}
.clipboard {
width:200px;
height:200px;
background:green;
}
img {
-webkit-user-select:none;
}
&#13;
<div class="clipboard"></div>
<div class="images">
<img src="http://i.stack.imgur.com/NghNQ.jpg" />
</div>
&#13;