通过javascript更改类时,CSS转换不起作用

时间:2014-05-20 12:25:13

标签: css-transitions

我有一个隐藏的div #about。通过单击链接#clickme,div将被函数取消隐藏。不幸的是,CSS转换(不透明度)不起作用,虽然它应该保持两个类.hide和.unhide包括转换。有什么想法吗?

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>

1 个答案:

答案 0 :(得分:3)

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

如果您移除display:none并仅转换opacity属性,效果将起作用。

<强> 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