I am trying to make multiple drag and drop areas. I am trying to add listeners for a "drop-zone" class (for every element with this class).
我正在尝试制作多个拖放区域。我正在尝试为“drop-zone”类添加侦听器(对于具有此类的每个元素)。
var dropZone = document.getElementById('some_area'); // ok
// var dropZone = document.getElementByClassName('drop-zone'); // not working
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dropZone.addEventListener('drop', function(e) {
var target_img = $(this).find('img');
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) { // finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
target_img.attr('src',e2.target.result);
target_img.addClass('full-preview');
}
reader.readAsDataURL(file); // start reading the file data.
} } });
1 个解决方案
#1
2
You need to query for all elements that have the specific class.
您需要查询具有特定类的所有元素。
// Returns a list of the elements within the document
// that match the specified 'drop-zone' class.
var dropZones = document.querySelectorAll('.drop-zone');
for (var i = 0; i < dropZones.length; i++) {
// Add the event listeners for each element of the list.
dropZones[i].addEventListener('dragover', function (e) {
// ...
});
dropZones[i].addEventListener('drop', function (e) {
// ...
});
}
#1
2
You need to query for all elements that have the specific class.
您需要查询具有特定类的所有元素。
// Returns a list of the elements within the document
// that match the specified 'drop-zone' class.
var dropZones = document.querySelectorAll('.drop-zone');
for (var i = 0; i < dropZones.length; i++) {
// Add the event listeners for each element of the list.
dropZones[i].addEventListener('dragover', function (e) {
// ...
});
dropZones[i].addEventListener('drop', function (e) {
// ...
});
}