vue实现5*5宫格当鼠标滑过选中的正方形背景颜色统一变色
1、实现的效果
2、完整代码展示
<template>
<div id="app" @mouseleave="handleMouseLeave({row: 0, col: 0 })">
<div v-for="rowItem in squareNumber" :key="rowItem">
<div class="row-list">
<div
v-for="colItem in squareNumber"
:key='colItem'
:class="['col-item', `${rowItem}-${colItem}`]"
@mouseenter="handleMouseEnter({row: rowItem, col:colItem })"
@mouseleave="handleMouseLeave({row: rowItem, col:colItem })"
></div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
squareNumber: 5
}
},
methods: {
handleMouseEnter(obj) {
const {row, col} = obj;
for(let rowItem = 1; rowItem <= row; rowItem++ ) {
for(let colItem = 1; colItem <= col; colItem ++) {
const element = document.getElementsByClassName(`${rowItem}-${colItem}`);
if(element) {
Array.from(element).forEach(item => {
item.style.background = 'red';
})
}
}
}
},
handleMouseLeave(obj) {
const {row, col} = obj;
for(let rowItem = 1; rowItem <= this.squareNumber; rowItem++ ) {
for(let colItem = 1; colItem <= this.squareNumber; colItem ++) {
const element = document.getElementsByClassName(`${rowItem}-${colItem}`);
if(element) {
Array.from(element).forEach(item => {
item.style.background = 'none';
})
}
}
};
if(!row || !col) {
this.handleMouseEnter({row: row - 1, col: col - 1})
}
}
}
}
</script>
<style>
#app {
border-top:1px solid black;
border-left: 1px solid black;
}
.row-list {
display: flex;
}
.col-item {
width: 30px;
height: 30px;
border-right: 1px solid black;
border-bottom: 1px solid black;
}
</style>
以上代码粘贴赋值即可使用