2012-04-10 93 views
1

我想创建一个菜单,如在redhotchilipeppers.com上。当您将链接悬停在右上角时,整个页面的背景颜色会发生变化。原始图像仍然在后面,它只是颜色的变化。jQuery:当鼠标悬停链接时,动画(淡入淡出)背景颜色或div中的图像?

下面你可以看到我是如何实现它的。这是淡淡的方式太慢,当我悬停一个链接,然后另一首先淡化到第一个链接bg颜色,然后回到正常,然后到第二个链接bg颜色。在redhotchilipeppers.com上,bg颜色马上消失。

下面的代码我用现在:

<head> 
<style> 
body { 
margin:0 auto; 
top:0; 
left:0; 
height:100%; 
width:100%; 
background:url(images/bg.jpg); 
} 

#container { 
width:100%; 
height:100%; 
display:block; 
position:absolute; 
top:0; 
left:0; 
opacity:0.4; 
filter:alpha(opacity=40); 
-moz-opacity: 0.4; 
background-color:#fff; 
z-index:-1; 
} 

.link { 
position:inherit; 
z-index:1; 
float:right; 
padding-top:100px; 
} 
</style> 
</head> 

<body> 
<div id="container"></div> 
<div class="link"> 
<a href="" id="linktomouseover"><img src="images/menu_start.png" alt="" /></a><a href="" id="linktomouseover2"><img src="images/menu_contactus.png" alt="" /></a> 
</div> 

<script> 
jQuery('#linktomouseover').hover(function() { 
jQuery('#container').animate({ backgroundColor: "#2154b9"}, 500); 
}).mouseleave(function(){ 
jQuery('#container').animate({ backgroundColor: "#ffffff"}, 500); 
}); 

jQuery('#linktomouseover2').hover(function() { 
jQuery('#container').animate({ backgroundColor: "#ac1c27"}, 500); 
}).mouseleave(function(){ 
jQuery('#container').animate({ backgroundColor: "#ffffff"}, 500); 
}); 
</script> 
</body> 

我在做什么错?或者是解决这个问题的更好方法?

+1

也许被复制..看一看这里http://stackoverflow.com/questions/8478685/change-div-background-image-on-hover-with-fade – 2012-04-10 13:48:08

回答

3

令人惊讶的是,jQuery不会动画背景颜色(没有插件)。最简单的方法是改变类与CSS和使用CSS转换,而不是像这样:

$('#linktomouseover').hover(function() { 
    $('#container').addClass('hover1') 
}, function() { 
    $('#container').removeClass('hover1') 
}); 

#container { 
    transition: background-color 0.5s; 
    -moz-transition: background-color 0.5s; 
    -webkit-transition: background-color 0.5s; 
    -o-transition: background-color 0.5s; 
} 

的jsfiddle:http://jsfiddle.net/kkzLW/

它更多的语义反正:)

+0

哇!这很好。感谢您的快速回答。但我注意到的一件事是,淡入淡出在Internet Explorer中不起作用。有没有解决这个问题的方法? – StreamAlex 2012-04-10 14:24:48