【问题标题】:Fading effect in CSS not working when the div closesdiv关闭时CSS中的淡化效果不起作用
【发布时间】:2016-06-12 05:39:59
【问题描述】:

当我单击切换按钮并隐藏 div 时,它会突然关闭而没有褪色动画。我怎么了?

我也想隐藏带有淡入淡出效果的 div。错过了什么?

CSS:

@-webkit-keyframes fadeIn { from { opacity:0; opacity: 1\9; /* IE9 only */ } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; opacity: 1\9; /* IE9 only */ } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; opacity: 1\9; /* IE9 only */ } to { opacity:1; } }

.fade-in {
    opacity:0;  /* make things invisible upon start */
    -webkit-animation:fadeIn ease-in 1;  /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
    -moz-animation:fadeIn ease-in 1;
    animation:fadeIn ease-in 1;

    -webkit-animation-fill-mode:forwards;  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -moz-animation-fill-mode:forwards;
    animation-fill-mode:forwards;

    -webkit-animation-duration:1s;
    -moz-animation-duration:1s;
    animation-duration:1s;
}

.fade-in.one {
-webkit-animation-delay: 0.2s;
-moz-animation-delay: 0.2s;
animation-delay: 0.2s;
}

HTML:

<a onclick="toggle_visibility('foo');">Toggle Foo</a>
   <div id="foo" style="display:none;" class="fade-in one">
      Here I am toggling the display text
   </div>

Javascript:

<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'none')
          e.style.display = 'block';
       else
          e.style.display = 'none';
    }
//-->
  </script>

【问题讨论】:

  • display 不是动画或过渡属性。
  • 好的。您能想到的任何其他技术可以实现这一目标吗?我只是想用一点动画来切换一个 div。

标签: javascript html css css-transitions


【解决方案1】:

如果您想进行其他调整,请告诉我。

function toggle(id) {
    var e = document.getElementById(id); 
    e.style.display = "block";  
    setTimeout(function(){ e.classList.toggle('visible') }, 1);        
}


function transition(id){

    var el = document.createElement("temp"); 
    var transitions = {
      'transition':'transitionend'
    }

    for(t in transitions){
        if( el.style[t] !== undefined ){
            return transitions[t];
        }
    }
}

document.getElementById("foo").addEventListener(transition("foo"), function() {
  if(!this.classList.contains("visible")) {
      this.style.display='none';
  }
});
#foo.visible {
  opacity: 1;
}

#foo { 
  opacity: 0;
  -webkit-transition: opacity 2s;
  transition: opacity 2s;
}
<a onclick="toggle('foo')" class="toggle">Toggle Foo</a>
<div id="foo">
  Here I am toggling the display text
</div>

【讨论】:

  • 我们可以不使用 jquery 而使用普通的 javascript 吗?我没有使用任何 JS 框架。
  • 我刚刚通过在 div 中添加更多纯文本来更新您的代码。产生的空白有什么解决办法吗?
  • 花了一些时间,但你来了。
猜你喜欢
  • 1970-01-01
  • 2014-09-14
  • 2023-03-19
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2012-01-29
相关资源
最近更新 更多