Vue3 Typescript 实现类似 Windows 鼠标框选文件 div 效果
首先,需要安装 Vue3 和 Typescript,并在 Vue 组件中引入以下代码:
<template>
<div class='box' @mousedown='startSelection' @mousemove='handleSelection' @mouseup='stopSelection'>
<div class='item' v-for='item in items' :class='{selected: item.selected}' :style='{left: item.x + 'px', top: item.y + 'px'}'>{{item.name}}</div>
</div>
</template>
<script lang='ts'>
import { ref } from 'vue'
interface Item {
name: string;
x: number;
y: number;
selected: boolean;
}
export default {
setup() {
const items = ref<Item[]>([
{name: 'Item 1', x: 50, y: 50, selected: false},
{name: 'Item 2', x: 150, y: 150, selected: false},
{name: 'Item 3', x: 250, y: 250, selected: false},
{name: 'Item 4', x: 350, y: 350, selected: false},
{name: 'Item 5', x: 450, y: 450, selected: false}
])
let startX = 0
let startY = 0
let isSelecting = false
const startSelection = (e: MouseEvent) => {
startX = e.pageX
startY = e.pageY
isSelecting = true
}
const handleSelection = (e: MouseEvent) => {
if (isSelecting) {
const box = document.querySelector('.box')
const itemsArray = [...items.value]
const left = Math.min(startX, e.pageX) - box.offsetLeft
const top = Math.min(startY, e.pageY) - box.offsetTop
const width = Math.abs(startX - e.pageX)
const height = Math.abs(startY - e.pageY)
itemsArray.forEach((item) => {
item.selected = item.x >= left && item.x <= left + width && item.y >= top && item.y <= top + height
})
items.value = itemsArray
}
}
const stopSelection = () => {
isSelecting = false
}
return {
items,
startSelection,
handleSelection,
stopSelection
}
}
}
</script>
<style>
.box {
position: relative;
width: 500px;
height: 500px;
background-color: #eee;
}
.item {
position: absolute;
width: 100px;
height: 100px;
background-color: #ccc;
border: 1px solid #999;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
}
.selected {
background-color: #333;
color: #fff;
}
</style>
在这个例子中,我们使用了ref来声明items数组。items数组包含了一些元素,每个元素都有一个名称name,一个横坐标x,一个纵坐标y,以及一个布尔值selected,表示该元素是否被选中。
我们还定义了startX和startY来记录鼠标框选的起始位置,以及一个布尔值isSelecting来表示是否正在进行框选。
在模板中,我们使用了一个名为box的div来包含所有的元素。当鼠标按下时,我们调用startSelection方法,记录起始位置。当鼠标移动时,我们调用handleSelection方法,计算出选框的位置和大小,然后判断每个元素是否被选中。最后,当鼠标松开时,我们调用stopSelection方法,表示框选结束。
在样式中,我们定义了选框和元素的样式。当一个元素被选中时,我们给它添加一个selected类,改变它的背景色和文字颜色。
这个例子可以帮助我们理解如何使用 Vue3 和 Typescript 实现类似于 Windows 鼠标框选文件 div 效果。
原文地址: https://www.cveoy.top/t/topic/nSqw 著作权归作者所有。请勿转载和采集!