当"拖动" Chrome中的图片

时间:2018-05-03 19:08:01

标签: javascript jquery

我发现了几个类似的问题,但都与按钮有关。这有点不同。在下面的示例中,我在非图像元素上的mouseup之后得到mousedown。但是,当我mousedown一个图像元素时,我从未收到过该事件。



$(document).on('mousedown','.draggable', function() {
  console.log("Clicked " + $(this).data('type'));
});

$(document).on('mouseup','.dropzone', function(e) {
  console.log("Dropped");
});

.dropzone {
 height: 100px;
 width: 200px;
 border: 1px solid blue;
 text-align: center;
}

div {
user-select: none;
}

.il {
display: inline-block;
vertical-align: top;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="draggable il" data-type="image" src="https://imgur.com/xTFOquF.png">
<div class="draggable il" data-type="text">No, drag me!</div>
<div class="dropzone il">Drop stuff here</div>
&#13;
&#13;
&#13;

如何制作,以便在图片mouseup之后收到mousedown个事件?

1 个答案:

答案 0 :(得分:3)

不使用mouseup,而是使用为此目的而构建的html drag and drop。你的所有可拖动元素都必须设置draggable = true,你需要防止dragover和drop事件的默认值。

$(".draggable").on('mousedown', function(e) {
  console.log("Clicked " + $(this).data('type'));
});

$(".dropzone").on('drop', function(e) {
  e.preventDefault();  
  console.log("Dropped");
});

$(".dropzone").on('dragover', function(e) {
  e.preventDefault();  
});
.dropzone {
 height: 100px;
 width: 200px;
 border: 1px solid blue;
 text-align: center;
}

div {
user-select: none;
}

.il {
display: inline-block;
vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="draggable il" draggable="true" data-type="image" src="https://imgur.com/xTFOquF.png">
<div class="draggable il" draggable="true" data-type="text">No, drag me!</div>
<div class="dropzone il">Drop stuff here</div>

如果你需要使用mouseup,你可以在mousedown事件上使用e.preventDefault(),但这也会阻止你的浏览器显示拖动。

$(document).on('mousedown','.draggable', function(e) {
  e.preventDefault();
  console.log("Clicked " + $(this).data('type'));
});

$(document).on('mouseup','.dropzone', function(e) {
  console.log("Dropped");
});
.dropzone {
 height: 100px;
 width: 200px;
 border: 1px solid blue;
 text-align: center;
}

div {
user-select: none;
}

.il {
display: inline-block;
vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="draggable il" data-type="image" src="https://imgur.com/xTFOquF.png">
<div class="draggable il" data-type="text">No, drag me!</div>
<div class="dropzone il">Drop stuff here</div>

您还可以在图片上设置draggable=false以获得相同的效果