2013-10-28 175 views
1

根據一本書,下面的例子應該淡入並退出菜單,但相反,菜單立即消失。我相信問題是display: none以某種方式生效太早,但我不確定,因爲它在動畫中說display: block點擊顛倒CSS3動畫

我能做些什麼來使灰色div淡出而不是消失?只有使用CSS的動畫纔是首選。

CSS

a { 
    color: white; 
    text-align: center; 
} 

.bar { 
    height: 20px; 
    background: red; 
} 

.div { 
    background: silver; 
    padding: 10px; 
} 

@-webkit-keyframes fade { 
    0% { 
    opacity: 0; 
    display: block; 
    } 

    100% { 
    opacity: 1; 
    display: block; 
    } 
} 

@keyframes fade { 
    0% { 
    opacity: 0; 
    display: block; 
    } 

    100% { 
    opacity: 1; 
    display: block; 
    } 
} 

.hidden { 
    display: none; 
    -webkit-animation: fade 2s reverse; 
    animation: fade 2s reverse; 
} 

.shown { 
    display: block; 
    -webkit-animation: fade 2s; 
    animation: fade 2s; 
} 

HTML

<div class="bar"> 
    <a href="#" class="click">Click Me</a> 
    <div class="div shown"> 
     <p>Hello</p> 
    </div> 
</div> 

jQuery的

$(function() { 
    $div = $(".div"); 

    var menu = function() { 
     if ($div.hasClass("shown")) { 
      $div.removeClass("shown"); 
      $div.addClass("hidden"); 
     } else { 
      $div.removeClass("hidden"); 
      $div.addClass("shown"); 
     } 

    } 

    menu(); 

    $(".click").bind("click", menu); 

}); 

小提琴:http://jsfiddle.net/hFdbt/1/

+0

關鍵幀只從IE10和支持。我看不出沒有理由不僅僅使用JavaScript。無論如何,你依靠javascript來進行點擊事件,所以你從使用CSS動畫中獲益匪淺。 – jah

+0

你需要改變顯示:none to opacity:0 [http://jsfiddle.net/hFdbt/5/](http://jsfiddle.net/hFdbt/5/) –

+0

將display屬性設置爲'none'將會終止應用於元素及其後代的任何正在運行的動畫 –

回答

2

正如我在我的評論,你可能只是藏漢使用jQuery它說。

jQuery的

$(".click").on("click", function() { 
    $(".div").fadeToggle("slow"); 
}); 

HTML

<div class="bar"> 
    <a href="#" class="click">Click Me</a> 
    <div class="div shown"> 
     <p>Hello</p> 
    </div> 
</div> 

的CSS

a { 
    color: white; 
    text-align: center; 
} 

.bar { 
    height: 20px; 
    background: red; 
} 

.div { 
    background: silver; 
    padding: 10px; 
    display: none; 
} 

新小提琴:http://jsfiddle.net/QvpS3/

+2

我不知道。它看起來對我是正確的。有人可能會拒絕你,因爲他說CSS3動畫是首選。 – dowomenfart

0

由於無法顯示元件過渡(THI它是一個布爾型或枚舉,只有「true」和「false」,因爲沒有true。5),你必須使用其他方法來隱藏元素。

在這種fiddlehttp://jsfiddle.net/3n1gm4/Q5TBN/)我用max-height財產和overflow: hiddentransition一起設置延遲。

.hidden { 
    -webkit-animation: fade 2s reverse; 
    animation: fade 2s reverse; 

    -webkit-transition: 0s all 2s; /* delay this the duration of the animation */ 
    transition-delay: 0s all 2s; 
    max-height: 0; 
    padding: 0; 

    overflow: hidden; 

} 

.shown { 
    -webkit-animation: fade 2s; 
    animation: fade 2s; 
    max-height: 5000px; /* some number way bigger than it will ever be to avoid clipping */ 
} 

學分:Transitions on the display: property