[英]Changing CSS properties of an element while a file is being dragged
我在我的 Vue JS Web 应用程序上设置了一个拖放框。 该元素是一个简单的 div,它在将文件拖放到文件上时处理文件。
我使用https://www.raymondcamden.com/2019/08/08/drag-and-drop-file-upload-in-vuejs作为指导。
HTML:
<div v-if="status == 'upload'">
<h3> Please fill the data sheet and upload it here!</h3>
<div class="downbox" @drop.prevent="addFile" @dragover.prevent>
<span style="font-size: 60px"><font-awesome-icon icon='cloud-upload-alt'/></span>
<br>
Click to Browse
<br>
or Drag and Drop a File Here
</div>
</div>
JS:
addFile: function(e){
let droppedFiles = e.dataTransfer.files;
if ((droppedFiles[0].name).slice(-5) !== '.xlsx') {
this.$swal({
text: "Please upload a file of type .xlsx",
title: "Incorrect File Type!",
icon: "error",
})
this.status = 'upload'
}
else {
this.file = droppedFiles
this.status = 'show'
}
},
removeFile: function(){
this.file = null
this.status = 'upload'
}
CSS:
.downbox {
width: 500px;
border-radius: 50px;
border-width: 6px;
border-color: white;
border-style: dashed;
background-color: #7a2ab3;
padding: 10px;
font-size: 25px;
font-weight: bold;
transition: 0.6s;
margin-left: auto;
margin-right: auto;
}
.downbox:hover{
background-color: #c56bc5;
}
如您所见,当您将鼠标悬停在 div 上时,背景颜色会发生变化。
但是,当我将文件拖到 div 上时,这种颜色变化不会出现。 因此,如果您单击拖动文件,我不知道它是否不算作“:悬停”。
无论哪种方式,我都想知道我可以在代码中添加什么,以便在将文件拖到 div 上时更改 CSS 背景颜色属性。
我使用以下解决方案(此处简化):
<template>
<div ref="drag" :class="{over: isOver}">
...
</div>
</template>
<script>
...
mounted () {
// add the needed event listeners to the container
this.$refs.drag.addEventListener("dragover", () => {
this.isOver = true; // add class on drag over
});
this.$refs.drag.addEventListener("dragleave", () => {
this.isOver= false; // remove class on drag leave
});
}
</script>
<css>
.over {...}
</css>
你可以监听dragenter
和dragleave
事件来处理这个。 但是,如果您的放置目标元素中有其他元素,则可能会很棘手,因为它们会触发您想要忽略的放置目标上的dragleave
事件。 但是这样的事情应该有效:
<div :class="['downbox', drag_over ? 'over' : '']"
@dragenter="dragEnter"
@dragleave="dragLeave"
@dragover.prevent
@drop.prevent="addFile"
>
<div ref="others">
<span style="font-size: 60px"><font-awesome-icon icon='cloud-upload-alt'/></span>
<br>
Click to Browse
<br>
or Drag and Drop a File Here
</div>
</div>
在您的事件处理程序中,使用over_others
来决定是否将drag_over
设置为false
,如果您仍在拖动子元素,您不希望这样做。 (另请参阅有关 Vue $refs的信息)
您可能对 60px 跨度和 font-awesome-icon 有更多困难,但如果它们给您带来麻烦,您应该能够将相同的原则扩展到这些元素。
data() {
return {
drag_over: false, // dragging over the target OR any child element
over_others: false, // dragging over a child element
}
},
methods: {
dragEnter(e) {
if(e.target === this.$refs.others) this.over_others = true
else this.drag_over = true
},
dragLeave(e) {
if(e.target === this.$refs.others) this.over_others = false
else if(!this.over_others) this.drag_over = false
},
// ...
}
并添加 css 类:
.downbox:hover,
.downbox.over {
background-color: #c56bc5;
}
查看此解决方案,显然您必须使用 X 和 Y 坐标:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.