2016-11-12 55 views
1

我前几天读了一篇有趣的文章,并试图将其应用到我的工作流程中。使用不透明度和变换的CSS动画

https://blog.gyrosco.pe/smooth-css-animations-7d8ffc2c1d29#.5a2q978fv

一个被提到的概念是只动画元素的不透明度和变换的思想。过去几天我一直在实施这个想法,并发现它非常棒。

我遇到过的一个问题是,如果元素处于不透明度0,则包含的父元素仍将应用子元素的空间。我试图通过缩放子元素来除去空间,但几乎没有,但空间仍然是持久的。

我很好奇,如果有人以这种方式工作,并有建议如何动画父元素与子元素一起增长?

function showHiddenBox() { 
 
    let hiddenBox = document.querySelector('.hiddenbox') 
 

 
hiddenBox.setAttribute('data-state', hiddenBox.getAttribute('data-state') === 'hidden' ? 'visible' : 'hidden'); 
 
}
.parentbox { 
 
    width: 200px; 
 
    background-color: #564d49; 
 
} 
 
.showingbox { 
 
    display: flex; 
 
    align-content: flex-start; 
 
    align-items: center; 
 
    justify-content: center; 
 
    width: 100%; 
 
    height: 100px; 
 
    background-color: #63cdff; 
 
} 
 
.hiddenbox { 
 
    width: 100%; 
 
    height: 100px; 
 
    transition: all 1s; 
 
    background-color: pink; 
 
} 
 
.hiddenbox[data-state="hidden"] { 
 
    opacity: 0; 
 
    transform: scaleY(.1) translateY(-50px); 
 
    transform-origin: top; 
 
} 
 
.hiddenbox[data-state="visible"] { 
 
    opacity: 1; 
 
}
<div class="parentbox"> 
 
    <div class="showingbox"> 
 
    <button onclick="showHiddenBox()">Click Me</button> 
 
    </div> 
 
    <div class="hiddenbox" data-state="hidden"></div> 
 
</div>

为了进一步说明自己,我已经创建了这个片段。我想创建一个只有不透明度和变换的动画,其中父元素的棕色不显示,但父元素将在创建子元素时展开。

回答

1

function showHiddenBox() { 
 
    let hiddenBox = document.querySelector('.hiddenbox') 
 

 
hiddenBox.setAttribute('data-state', hiddenBox.getAttribute('data-state') === 'hidden' ? 'visible' : 'hidden'); 
 
}
.parentbox { 
 
    width: 200px; 
 
    background-color: #564d49; 
 
} 
 
.showingbox { 
 
    display: flex; 
 
    align-content: flex-start; 
 
    align-items: center; 
 
    justify-content: center; 
 
    width: 100%; 
 
    height: 100px; 
 
    background-color: #63cdff; 
 
} 
 
.hiddenbox { 
 
    width: 100%; 
 
    height: 100px; 
 
    transition: all 1s; 
 
    background-color: pink; 
 
} 
 
.hiddenbox[data-state="hidden"] { 
 
    max-height: 0; 
 
    transform: scaleY(.1) translateY(-50px); 
 
    transform-origin: top; 
 
} 
 
.hiddenbox[data-state="visible"] { 
 
    max-height: 300px; 
 
}
<div class="parentbox"> 
 
    <div class="showingbox"> 
 
    <button onclick="showHiddenBox()">Click Me</button> 
 
    </div> 
 
    <div class="hiddenbox" data-state="hidden"></div> 
 
</div>

使用最大高度,而不是不透明度。过度夸大最大高度。取决于它如何为你工作。这是你想要的吗?

+0

是的,这将工作。我很好奇,如果有可能只是不透明和改造。但我不必是最纯粹的; P说实话,我没有看到任何可能的方式来处理这两种风格。我想我会把问题放在那里,看看有没有人有更好的主意。 – Jleibham

+0

你不能。由于不透明度只是调整元素及其子元素的透明度。如果你想有更好的表现。使用GreenSock Tweenmax。它很容易使用。 :):D –