知识点
mousemove与mouseenter的区别在于mousemove会触发事件冒泡,mouseenter不会,mouseleave同理。
mousemove会触发事件冒泡,因此鼠标在范围区域内移动时会一直触发。
mouseenter只触发一次,鼠标移入后触发,鼠标移出后不再触发。
<template>
<div class="collapse">
<!-- 固定展示区域 -->
<div class="collapse-heade">
<slot name="collapseHeade"></slot>
</div>
<!-- 动态展示区域 -->
<div class="collapse-body" :style="{ 'height': collHeight + 'px', 'transition': 'all 0.5s ease' }">
<slot name="collapseBody"></slot>
</div>
<div class="collapse-bar" @click="onSwitch">
<div class="collapse-bar-box">
<div class="collapse-bar-box-con">
<i :class="['icon', icon]"></i>
<span class="text">{{ text }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
collHeight: 0,
show: false,
showText: false,
text: '展示更多',
icon: 'el-icon-caret-bottom'
}
},
mounted() {
const box = document.querySelector('.collapse-bar-box')
/*
* mousemove与mouseenter的区别在于mousemove会触发事件冒泡,mouseenter不会,mouseleave同理
* mousemove会触发事件冒泡,因此鼠标在范围区域内移动时会一直触发。
* mouseenter只触发一次,鼠标移入后触发,鼠标移出后不再触发
*/
box.addEventListener('mouseenter', function (ev) {
this.querySelector('.collapse-bar-box-con').style.transform = 'translateX(-20px)'
this.querySelector('.collapse-bar-box-con>.icon').style.color = '#36CFC9'
this.querySelector('.collapse-bar-box-con>.text').style.opacity = '1'
})
box.addEventListener('mouseleave', function () {
this.querySelector('.collapse-bar-box-con').style.transform = 'translateX(20px)'
this.querySelector('.collapse-bar-box-con>.icon').style.color = '#d3dce6'
this.querySelector('.collapse-bar-box-con>.text').style.opacity = '0'
})
},
methods: {
onSwitch() {
this.show = !this.show
if (this.show) {
this.collHeight = 0
const list = Array.from(document.querySelector('.collapse-body').children)
list.forEach((item) => {
this.collHeight += item.offsetHeight
})
this.icon = 'el-icon-caret-top'
this.text = '隐藏内容'
} else {
this.collHeight = 0
this.icon = 'el-icon-caret-bottom'
this.text = '展示更多'
}
}
}
}
</script>
<style lang="scss" scoped>
.collapse {
border-radius: 3px;
.collapse-heade {}
.collapse-body {
overflow: hidden;
}
.collapse-bar {
height: 44px;
width: 100%;
padding: 0 16px;
box-sizing: border-box;
.collapse-bar-box {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ebebeb;
border-radius: 4px;
cursor: pointer;
.collapse-bar-box-con {
transition: transform 0.3s;
i {
font-size: 16px;
font-weight: 500;
color: #d3dce6;
transition: color 0.3s;
}
span {
margin-left: 12px;
font-size: 14px;
font-weight: 400;
color: #36CFC9;
opacity: 0;
transition: opacity 0.3s;
}
}
}
}
}
</style>