我有以下情況:我正在顯示多個div框,每個框都width因背景關系而異。例如:
.demand-2 {
width: 29%;
}
.demand-3 {
width: 43%;
}
A divwithdemand-2應該只29%屬于它的 parent width。
現在,有一個按鈕可以將所有框增加到一個widthof 100%。使用以下 CSS,我確保過渡是平滑的:
maxLevelOff {
animation-duration: 1s;
animation-name: maxOff;
animation-fill-mode: forwards;
}
@keyframes maxOff {
from {
width: 29;
}
to {
width: 100%;
}
}
但是,正如您所看到的,這非常有效,只是demand-2因為我不得不對其進行硬編碼。
我現在的問題是,有沒有辦法可以動態地做到這一點?否則我必須為所有不同的東西創建一個影片,widths這看起來很乏味。這也應該反過來。換句話說,如果我再次單擊該按鈕,所有的框都應該從100%回到原來的大小。
uj5u.com熱心網友回復:
作為替代方案,您也可以使用 css 轉換。當寬度改變時,它會平滑地過渡到新的寬度。您只需要為.full-width每個.demand您想要 100% 寬度的類添加一個類。
我在下面提供了一個簡單的演示。如果您單擊一次按鈕,寬度會擴大,如果您再次單擊它,它將回傳到原始寬度。
let button = document.querySelector('button');
button.addEventListener('click', () => {
let demand = document.querySelectorAll('.demand');
demand.forEach(el => {
if(el.classList.contains('full-width')) el.classList.remove('full-width')
else el.classList.add('full-width')
});
});
.demand {
height: 100px;
transition: width 0.3s ease-in;
}
.demand-2 {
background: blue;
width: 29%;
}
.demand-3 {
background: red;
width: 49%;
}
.demand-4 {
background: green;
width: 69%;
}
.demand.full-width {
width: 100%;
}
<div class="demand demand-2"></div>
<div class="demand demand-3"></div>
<div class="demand demand-4"></div>
<button>Click</button>
uj5u.com熱心網友回復:
你不需要在你的keyframe
@keyframes maxOff {
to {
width: 100%;
}
}
例如
@keyframes maxOff {
to {
width: 100%;
}
}
.first {
width: 300px;
height: 100px;
background: red;
animation: maxOff 1s ease infinite alternate;
}
.second {
width: 100px;
height: 100px;
background: blue;
animation: maxOff 1s ease infinite alternate;
}
.third {
width: 50%;
height: 100px;
background: yellow;
animation: maxOff 1s ease infinite alternate;
}
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
如果你想要后退影片,你應該有 2 個獨立keyframe的(一個用于轉發,一個用于后退)
使用此解決方案,您需要使用 javascript 來處理click
例如(影片需要點擊泳道區域)
function activateAnimation(self) {
if(self.classList.contains("active")) {
self.classList.remove("active")
self.classList.add("deactive")
} else {
self.classList.add("active")
self.classList.remove("deactive")
}
}
@keyframes maxOff {
to {
width: 100%;
}
}
@keyframes maxBack {
from {
width: 100%;
}
}
.third {
width: 50%;
height: 100px;
background: yellow;
}
.third.active {
animation: maxOff 1s ease 1 forwards;
}
.third.deactive {
animation: maxBack 1s ease 1 alternate;
}
<div class="third" onclick="activateAnimation(this)"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451936.html
上一篇:網格中的按鈕,間隙中有箭頭
