用纯JS切换div

时间:2014-02-06 20:30:53

标签: javascript css3 css-transitions

场景:一个主容器,一个具有不透明度1的子img和一个具有不透明度0的子跨度,两个绝对定位在相对定位的父div上。降低img的不透明度并同时增加跨度的不透明度。当不透明度超过某个阈值时,例如, 0.01和0.99分别隐藏/显示(显示:无;显示:内联块)img / span。然后是反向过程来显示img并隐藏跨度。什么是最好的解决方案(可能使用CSS3)来实现这一目标?

<div id="post-cont">
    <img id="post-img-1" class="post-img" src="small.jpg"/>
    <span id="post-txt-1" class="post-txt">Some text</span>
</div>

有一些workaround with JS,但它是滞后的,所以我想用CSS3和尽可能少的JS来解决这个问题。

2 个答案:

答案 0 :(得分:3)

CSS3

http://jsfiddle.net/SPmj5/7/

<div id="post-cont">
    <img id="post-img-1" class="post-img" src="http://placehold.it/250x250"/>
    <span id="post-txt-1" class="post-txt">Some text</span>
</div>


#post-cont {
    position: relative;
}

#post-cont img,
#post-cont span {
    display:block;
-o-transition: opacity .7s ease;
    -ms-transition: opacity .7s ease;
    -moz-transition: opacity .7s ease;
    -webkit-transition: opacity .7s ease;
    transition: opacity .7s ease;    
}

#post-cont img {
    position: absolute;
    top: 0;
    left: 0;
   opacity: 1;
}

#post-cont span {
    position: absolute;
    top: 100px;
    left: 80px;
   opacity: 0; 
}

#post-cont:hover img {
    opacity: 0;
}

#post-cont:hover span {
    opacity: 1;
}

请注意,IE8 / 9 http://caniuse.com/#search=transition

不支持转换

答案 1 :(得分:-1)

听起来有点褪色给我!我不认为你可以使用纯CSS3 ..

https://api.jquery.com/fadeToggle/