使用jQuery交叉淡入淡出背景图像

我希望通过hover元素来交叉淡化/过渡背景图像。 有可能吗? 我有一个具有背景图像的DIV元素,但当您将其hover时,背景图像会随着过渡/交叉渐变效果而变化。 在我的样式表上,我为hover状态指定了一个类。

这是DIV的正常或非hover状态。

 #crossfade DIV{ width: 100px; height: 100px; background-image: url('img/bg.jpg'); } 

下面是DIV的hover状态类。

 #crossfade DIV.hovered{ background-image: url('img/bg-1.jpg'); } 

然后我的jquery脚本如下:

 $(function(){ $('#crossfade').find('DIV').hover(function(){ $(this).addClass('hovered'); }, function(){ $(this).removeClass('hovered'); }); }); 

我的脚本只需简单切换背景图片。 现在我想要的是给它一个过渡效果或更像fadeIn / fadeOut效果。 就像之前的背景图像渐渐消失一样,下一个背景图像也会逐渐消失。

知道怎么做吗? 可能吗?

谢谢 :)

我花了很多时间对它进行故障排除,因为它也让我感兴趣。 学到了很多,以为我会和你分享。

第一:我不相信你可以使用addClassremoveClass 交叉淡化背景图像,因为你无法在逻辑上同时淡入淡出元素 。 (如果我错了,请有人教我)。

只是为了让你知道我知道你想要什么,我成功地完成了以下工作:

 $(".div-bkgrnd-1").hover(function() { $(this).fadeOut("slow",function() { $(this).addClass('div-bkgrnd-2').fadeIn("slow",function() { $(this).removeClass('div-bkgrnd-1'); }); }); }); 

但是,这并不能解决您的问题,即创建2个图像的交叉淡入淡出

您将看到fadeOut首先运行,然后添加新类,然后运行fadeIn ,并删除第一个类。 你不能同时运行fadeOutfadeIn (它会创建你正在寻找的交叉淡入淡出),因为如果你在fadeOut完成之前删除了第一个类,它就会中断动画。

这是一个我认为适合您的解决方案。

HTML:

 

jQuery的:

 $("#div1").hover(function() { $("#img").fadeToggle("slow"); }); 

注意:确保将鼠标hover在div上; 定位图像会导致一些奇怪的行为。

(此解决方案假设您希望图像在您hover时交叉渐变,然后在您hover时交叉淡化回原始图像。如果这是您想要的,将function更改为fadeOut将作为一次性工作。

如果您指定背景图像是因为需要其他内容可以放在前面,这可以使用z-index和包含div(以及上面的jQuery)轻松解决。

HTML:

 

CSS:

 #div1 { z-index: 1; position: absolute; background-image: image1; } #div2 { z-index: 2; position: relative; } 

像jQuery循环插件这样的库可以为你做这件事。 非常强大且易于使用。 你也可以使用回调来自己动手。 我相信这会奏效 – 我只编写了上半部分,但我认为你会得到这个想法。

 $(function(){ $('#crossfade').find('DIV').hover(function(){ $(this).fadeOut('slow', function() { $(this).addClass('hovered').fadeIn(); }); }, function(){ $(this).removeClass('hovered'); }); }); 

因为你愿意使用CSS3,所以不涉及jQuery呢?

简单解决方案

HTML:

 

CSS:

 #container div { background-image: url("img1.jpg"); } #container div img { opacity: 0; -webkit-transition: 500ms opacity; -moz-transition: 500ms opacity; -ms-transition: 500ms opacity; -o-transition: 500ms opacity; transition: 500ms opacity; } #container div img:hover { opacity: 1; } 

注意: -webkit-moz-ms-o前缀只是为了避免复杂性问题,但它应该在所有现代浏览器中都能正常工作。

剥离版本:

 #container div { background-image: url("img1.jpg"); } #container div img { opacity: 0; transition: 500ms opacity; } #container div img:hover { opacity: 1; } 

唯一的缺点是背景图像不会淡出,它将与img元素重叠,因此它对透明PNG无用。