通过javascript更改类时CSS过渡不起作用 [英] CSS transition not working when changing class by javascript

查看:55
本文介绍了通过javascript更改类时CSS过渡不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个隐藏的div #about。通过单击链接#clickme,div将被函数取消隐藏。不幸的是,CSS过渡(不透明性)无法正常运行,尽管它应同时包含.hide和.unhide两个类,包括过渡。有什么想法吗?

I have a hidden div #about. By clicking the link #clickme the div gets unhidden by a function. Unfortunately the CSS transition (opacity) is not working though it should keep both classes .hide and .unhide including the transitions. Any ideas?

HTML

<li><a id="clickme" href="javascript:unhide('about');">click me</a></li>

<div id="about" class="hide">
<p>lorem ipsum …</p>
</div>

CSS

.hide { 
display: none;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
-o-transition: opacity 3s;
transition: opacity 3s;
opacity:0;  
}   
.unhide { 
display: inline;
opacity:1;
}

SCRIPT

<script>
function unhide(divID) {
var element = document.getElementById(divID);
if (element) {
  element.className=(element.className=='hide')?'hide unhide':'hide';
}
}
</script>


推荐答案

您需要删除 display:none 。您实际上是在以两种方式隐藏元素- display:none opacity:0

You need to remove the display:none from the element. You're essentially hiding the element 2 ways - display:none and opacity:0.

如果删除 display:none 并仅转换 opacity 属性将起作用。

If you remove the display:none and only transition the opacity property the effect will work.

CSS

.hide { 
    -webkit-transition: opacity 3s;
    -moz-transition: opacity 3s;
    -o-transition: opacity 3s;
    transition: opacity 3s;
    opacity:0;  
}   

.unhide { 
    opacity:1;
}

function unhide(divID) {
  var element = document.getElementById(divID);
  if (element) {
    element.className = (element.className == 'hide') ? 'hide unhide' : 'hide';
  }
}

.hide {
  -webkit-transition: opacity 3s;
  -moz-transition: opacity 3s;
  -o-transition: opacity 3s;
  transition: opacity 3s;
  opacity: 0;
}

.unhide {
  opacity: 1;
}

<li><a id="clickme" href="javascript:unhide('about');">click me</a></li>

<div id="about" class="hide">
  <p>lorem ipsum …</p>
</div>

这是 jsFiddle ,显示了它的操作。

Here is a jsFiddle showing it action.

这篇关于通过javascript更改类时CSS过渡不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆