From my experience and this other answer here , you can not do fade of opacity between two background-image
using only CSS3.
What you would have to do is create two overlapping elements, with background-image
different, and animate their respective opacity
via CSS3 Animation.
If you really want to do it in JavaScript, this code is an example here, it does not use any very new functionality, it works in Chrome, Firefox and even in IE9:
<!DOCTYPE html>
<html lang="pt-br" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Teste</title>
<style type="text/css">
.container, .botao {
font: normal 16px tahoma;
text-align:center;
width: 150px;
height: 40px;
color:#FFF;
cursor: pointer;
display: inline-block;
vertical-align: bottom;
box-sizing: border-box;
-moz-box-sizing: border-box;
}
.container {
position: relative;
}
.botao {
padding:10px;
position: absolute;
left: 0px;
top: 0px;
}
.frente {
background: url(http://i.stack.imgur.com/5PWNy.png) 0 -100px;
z-index: 1;
}
.tras {
background: url(http://i.stack.imgur.com/5PWNy.png) 0 -150px;
z-index: 0;
}
.container:active .tras {
box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.76);
-webkit-box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.76);
-moz-transition: inset 0px 0px 10px rgba(0, 0, 0, 0.76);
-ms-transition: inset 0px 0px 10px rgba(0, 0, 0, 0.76);
-o-transition: inset 0px 0px 10px rgba(0, 0, 0, 0.76);
}
</style>
</head>
<body>
<span>Botão 1:</span>
<div class="container">
<div class="botao frente" style="opacity: 1;" id="el1">TESTE</div>
<div class="botao tras">TESTE</div>
</div>
<span>Botão 2:</span>
<div class="container">
<div class="botao frente" style="opacity: 1;" id="el2">TESTE 2</div>
<div class="botao tras">TESTE 2</div>
</div>
<script type="text/javascript">
function buttonMouseChanged(fadingIn) {
//Trabalhando com o Closure a nosso favor ;)
var _this = this, animate;
animate = function () {
var o = parseFloat(_this.style.opacity);
if (_this.fadingIn) {
o += 0.05;
if (o < 1)
setTimeout(animate, 1000 / 60);
else
o = 1;
} else {
o -= 0.05;
if (o > 0)
setTimeout(animate, 1000 / 60);
else
o = 0;
}
_this.style.opacity = o;
};
this.fadingIn = fadingIn;
setTimeout(animate, 1000 / 60);
}
function buttonMouseEnter() {
buttonMouseChanged.call(this, false);
}
function buttonMouseLeave() {
buttonMouseChanged.call(this, true);
}
function prepareButton(id) {
var btn = document.getElementById(id);
btn.onmouseenter = buttonMouseEnter;
btn.onmouseleave = buttonMouseLeave;
}
prepareButton("el1");
prepareButton("el2");
</script>
</body>
</html>
Notice how the value of opacity
of el1
, and el2
, is set to 1, so you can parseFloat()
always work.
To make the animation improve a bit, it would be interesting not to use a fixed value (such as 0.05) to add and subtract from opacity
, but a value proportional to the time elapsed since the last execution of the animate()
function. p>