CSS Transition没有缓和

时间:2015-04-12 12:01:55

标签: javascript css css3 css-transitions

关于这个问题有很多问题,但没有一个可以帮助我。

我试图根据按钮悬停来放松和缩小背景图像。 Here is the fiddle

HTML:
<div class="bg bg-home"></div>
<div class="main-menu" id="home">
  <a href="#">Home</a>
</div>

JS:
$('#home').hover(function() {
    $('.bg.bg-home').addClass('home-main-menu');
},function() {
    $('.bg.bg-home').removeClass('home-main-menu');
});

CSS:
html,body {
    height: 100%;
}
.bg {
  -webkit-transition: all 1s;
  transition: all 1s;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  opacity: 0;
}
.bg-home {
    position:absolute;
    left:0;
    top:0;
    z-index: -1; 
    width: 100%;
    height: 100%;
}
.home-main-menu {
  background: url("http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2013/1/11/1357921737290/Masterclass-in-HTML5-and--006.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  opacity: 1;
}

问题是背景图像很好,但不会缓和。我也尝试过只进行不透明度的转换,但结果相同。

有人可以解释一下我做错了吗?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以将背景图像切换为.bg-home本身。然后,在悬停时添加的类只需要影响不透明度,你就可以顺利地进行缓和。

看到这个小提琴: https://jsfiddle.net/Ltv58jmh/2/

.bg-home {
    position:absolute;
    left:0;
    top:0;
    z-index: -1; 
    width: 100%;
    height: 100%;
    background: url("http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2013/1/11/1357921737290/Masterclass-in-HTML5-and--006.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    opacity:0;
}
.home-main-menu {
    opacity: 1;
}