我正在尝试实现一个照片上传器,其中照片的顺序很重要。为了做到这一点,我试图实现一个拖放机制来交换他们的位置。我面临的问题是,我不能把图像放在彼此的顶部。我必须把它们放到div中来排序图像。下面是component.html代码:
<div class="container">
<div class="row">
<div class="col-12">
<input type="file" multiple (change)="onSelectFile($event)" />
</div>
<div class="col-12">
<div
class="photos-container"
(dragover)="onDragOver($event)"
(drop)="onDrop($event)"
>
<div
*ngFor="let image of images; index as i"
class="photo"
[draggable]="true"
(dragstart)="onDragStart(i, $event)"
style="background-color: black;"
>
<img [src]="image" style="width: 200px; height: 200px;" />
</div>
</div>
</div>
</div>
</div>
组件。它的代码是:
onSelectFile(event: any) {
if (event.target.files.length > 0) {
this.files = event;
const files = Array.from(event.target.files);
files.forEach((file: any) => {
const reader = new FileReader();
reader.onload = (e: any) => {
this.images.push(e.target.result);
};
reader.readAsDataURL(file);
this.imageChangedEvnt = event;
});
}
}
onDragStart(index: any, event: any) {
event.dataTransfer.setData("index", index);
}
onDragOver(event: any) {
event.preventDefault();
}
onDrop(event: any) {
const index = event.dataTransfer.getData("index");
const newIndex = Array.from(event.currentTarget.children).indexOf(
event.target
);
if (newIndex >= 0) {
const photo = this.images.splice(index, 1)[0];
this.images.splice(newIndex, 0, photo);
}
}
这里是最小可复制的演示:demo
我尝试了上面的代码,但我仍然不能将图像放在彼此的顶部。只有当我将图像放入排序div中时,交换才能工作。
在onDrop
const newIndex = Array.from(event.currentTarget.children).indexOf(event.target);
当你把一个图像放到另一个图像的顶部时,event.target
将是<img...../>
。
在这种情况下,您在数组<div>
中寻找indexOf
和<img>
,因此您的newIndex
显然等于-1
。
有两种方法可以越过
1。不应该在拖放区域放任何东西所以使用<img>
来处理翻译本身。更新app.component.html
<div class="container">
<div class="row">
<div class="col-12">
<input type="file" multiple (change)="onSelectFile($event)" />
</div>
<div class="col-12">
<div
class="photos-container"
(dragover)="onDragOver($event)"
(drop)="onDrop($event)"
style="
display: flex;
flex-direction: column;
align-items: center;
background-color: black;">
<img
[src]="image"
*ngFor="let image of images; index as i"
class="photo"
[draggable]="true"
(dragstart)="onDragStart(i, $event)"
style="width: 200px; height: 200px;"/>
</div>
</div>
</div>
</div>
2。句柄情况更棘手。更新onDrop
到
onDrop(event: any) {
const index = event.dataTransfer.getData("index");
let targetElement;
if (event.target.tagName === "IMG") {
targetElement = event.target.parentElement;
} else if (event.target.tagName === "DIV") {
targetElement = event.target;
}
const newIndex = Array.from(event.currentTarget.children).indexOf(
targetElement
);
if (newIndex >= 0) {
const photo = this.images.splice(index, 1)[0];
this.images.splice(newIndex, 0, photo);
}
}