block 和 none 問題
一些 CSS 屬性可以是影片的,也就是說,當它的值改變時,它可以以平滑的方式改變,
做折疊面板最簡單的方式是改變它的 block 或 none,這兩個屬性值不包含在可影片屬性中,詳見:CSS animated properties,所以,設定 CSS 影片(keyframes)或 transition 都是沒有效果的,
JS 輔助實作
這個時候就需要借助 JS 來實作折疊面板,首先,獲取折疊面板內容的高度,有了高度按照一定周期來逐步增加高度,或逐步減少高度,
<div >
<div >
<div @click="isToggled = !isToggled">
<div>
<slot name="icon" />
</div>
{{ text }}
</div>
<div @click="toggle">
<i-ep-arrow-down />
</div>
</div>
<div
@click="toggle"
:>
<div >
<i-ep-arrow-down />
</div>
</div>
</div>
setup
通過一個變數 isToggled 來判斷是否折疊過面板,content 是獲取面板內容的模板參考,height 是高度,對模板參考的高度進行設定,
// setup
const isToggled = ref(true);
const content = ref();
const height = ref();
// 把每一個折疊面板的高度都分成 10 份來間接性執行,執行完最后一幀之后設定 0,即不顯示內容
function toggleClose() {
let counter = 9;
let cHeight = height.value;
const interval = setInterval(() => {
cHeight -= height.value / 10;
content.value.style.height = `${cHeight.value}px`;
counter--;
if (counter == 0) {
content.value.style.height = `${0}px`;
// 已經折疊了面板
isToggled.value = https://www.cnblogs.com/Himmelbleu/archive/2023/03/03/false;
clearInterval(interval);
}
}, 10);
}
function toggleOpen() {
let counter = 9;
let cHeight = 0;
const interval = setInterval(() => {
cHeight += height.value / 10;
content.value.style.height = `${cHeight}px`;
counter--;
if (counter == 0) {
content.value.style.height = `${height.value}px`;
// 已經打開了面板
isToggled.value = true;
clearInterval(interval);
}
}, 10);
}
function toggle() {
if (isToggled.value) {
toggleClose();
} else {
toggleOpen();
}
}
// 組件內容渲染完成之后,獲取模板參考物件,計算高度,并插入到 CSS 樣式中
onMounted(() => {
height.value = $(content.value).height();
content.value.style.height = `${height.value}px`;
});
CSS 影片
.l-expandable__title {
border-left: 4px solid var(--el-color-primary);
}
.arrow {
transform: scale(0, 0);
}
.l-expandable__title:hover .arrow {
transform: scale(1, 1);
}
.arrow-up {
animation: arrow-up-animation 0.3s ease-in;
transform: rotate(180deg);
}
.arrow-down {
animation: arrow-down-animation 0.3s ease-in;
transform: rotate(0deg);
}
@keyframes arrow-up-animation {
@for $index from 0 to 10 {
#{$index * 10%} {
transform: rotate($index * 18deg);
}
}
}
@keyframes arrow-down-animation {
@for $index from 0 to 10 {
#{$index * 10%} {
transform: rotate(180deg - $index * 18deg);
}
}
}
.l-expandable__content {
overflow: hidden;
transition: var(--l-transition);
}
實作效果

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/545623.html
標籤:其他
下一篇:JS物件
