父级宽度自适应
1.父级限制最大宽度
2.子级竖着排放,每列的个数明确
3.父级的宽度跟随子级元素的个数变化宽度
tips: 因为父级要设置"background-color"属性,所以父级DIV必须要给明确的宽高,这就意味着纯CSS自适应宽度无法做到(好吧,是我做不到)
HTML
<template>
<div class="apps">
<div class="parent">
<ul
v-for="(item, index) in parentList"
:key="index"
@mouseover="mouseoverParent(index)"
@mouseout="mouseoutParent(index)"
class="parent-ul"
>
<li>触摸条件-{{ item }}</li>
</ul>
<div
class="other-div"
@mouseover="mouseoverOther()"
@mouseout="mouseoutOther()"
>
<ul v-for="(item, index) in mockContentList" :key="index">
<li>内容-{{ item }}</li>
</ul>
</div>
</div>
</div>
</template>
data
parentList: [1, 2, 3, 4, 5],
mockContentList: undefined,
index: 0, // 缓存左侧栏选择的第几项的index
width1: '120px',
width2: '240px',
width3: '360px',
width4: '480px'
JS
// 模拟从服务器获取'内容区域'List。此处用数字替代
getData(index) {
if (index === 1) {
this.mockContentList = 6
} else if (index === 2) {
this.mockContentList = 9
} else if (index === 3) {
this.mockContentList = 16
} else {
this.mockContentList = 22
}
},
// 判断'内容区域'有多少个,以此分配不同的空间(宽度)
setWidth() {
// 获取数组长度
// const lg = this.mockContentList.length
const lg = this.mockContentList
if (lg < 7) {
document.querySelector(
'.other-div'
).style = `width: ${this.width1}`
} else if (lg > 6 && lg < 13) {
document.querySelector(
'.other-div'
).style = `width: ${this.width2}`
} else if (lg > 14 && lg < 19) {
document.querySelector(
'.other-div'
).style = `width: ${this.width3}`
} else {
document.querySelector(
'.other-div'
).style = `width: ${this.width4}`
}
},
delWidth() {
document.querySelector('.other-div').style = 'width: 0'
},
setBackgroundColor(i) {
const style = 'background:#ff6700'
document.querySelector(`.parent > :nth-child(${i})`).style =
style
},
resetBackgroundColor(i) {
const style = 'background:#rgba(105, 101, 101, 0.6)'
document.querySelector(`.parent > :nth-child(${i})`).style =
style
},
mouseoverParent(index) {
const i = index + 1
this.index = i
this.getData(i)
this.setBackgroundColor(i)
this.setWidth()
},
mouseoutParent(index) {
const i = index + 1
this.index = i
this.resetBackgroundColor(i)
this.delWidth()
},
// 给左侧边栏添加背景样式
mouseoverOther() {
this.setBackgroundColor(this.index)
this.setWidth()
},
mouseoutOther() {
this.resetBackgroundColor(this.index)
this.delWidth()
}
SCSS
*{
list-style: none;
}
.apps {
position: absolute;
top: 50%;
left: 40%;
transform: translate(-50%, -50%);
}
.parent {
position: relative;
width: 200px;
height: 400px;
background: #b0b0b0;
text-align: center;
.parent-ul {
padding-top: 40px;
height: 40px;
width: 100%;
&:hover ~ .other-div {
width: 400px;
}
li {
font-size: 16px;
}
}
}
.other-div {
overflow: hidden;
height: 0;
transition: all 0.3s;
position: absolute;
width: 0; // 当元素内存在内容时,设置宽度才显示
height: 400px;
left: 200px;
top: 0;
background: palevioletred;
box-shadow: 5px 0 15px -5px rgba(0, 0, 0, 0.6);
display: inline-flex;
flex-wrap: wrap;
flex-direction: column;
align-content: flex-start;
&:hover {
width: 480px;
}
ul {
width: 120px;
height: 60px;
li {
font-size: 16px;
&:hover{
color: #fff
}
}
}
}