CSS transition not working when changing class by javascript

*爱你&永不变心* 提交于 2019-12-10 04:06:47

问题


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>

回答1:


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

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>

Here is a jsFiddle showing it action.



来源:https://stackoverflow.com/questions/23759794/css-transition-not-working-when-changing-class-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!