【问题标题】:jQuery: Animate (fade) background-color or image in div when hover a link?jQuery:悬停链接时在div中动画(淡化)背景颜色或图像?
【发布时间】:2012-04-22 19:38:45
【问题描述】:

我想在 redhotchilipeppers.com 上创建一个菜单。当您将链接悬停在右上角时,整个页面的背景颜色会发生变化。原始图像仍然在后面,只是颜色发生了变化。

您可以在下面看到我是如何尝试实现它的。它的褪色太慢了,当我悬停一个链接然后另一个链接时,它首先淡入第一个链接的背景颜色,然后恢复正常,然后恢复到第二个链接的背景颜色。在 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>

我做错了什么?还是有更好的方法来解决这个问题?

【问题讨论】:

标签: jquery html background hover jquery-animate


【解决方案1】:

令人惊讶的是,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/

无论如何它更符合语义:)

【讨论】:

  • 哇!那效果很好。感谢您的快速答复。但我注意到的一件事是褪色在 Internet Explorer 中不起作用。可能有解决办法吗?
猜你喜欢
  • 1970-01-01
  • 2013-09-16
  • 2014-07-24
  • 2018-08-28
  • 2012-01-27
  • 2019-06-23
  • 1970-01-01
  • 2012-03-05
  • 2011-10-23
相关资源
最近更新 更多