在hover时向背景图像添加淡入和淡出过渡

我在页面的侧边栏中有一个简单的导航系统,你可以在这里看到。

正如您可以看到当您将鼠标hover在侧边栏中的一个链接上时,背景图像会发生变化,因为我已在CSS中设置了不同的背景URL以hover。 我正在寻找一种添加过渡效果的简单方法,以便hover背景图像淡入淡出。 我尝试了几种jQuery方法但没有成功。 我想知道是否有一种方法可以使用jQuery或其他方法向后台URL图像添加淡入淡出过渡,或者是否必须使用其他方法来获得过渡效果。

谢谢,

缺口

如果没有一些澄清或一些示例代码,很难说你要做什么,但是你在寻找这样的东西吗?

$("#someElement").hover(function() { $(this).stop().fadeOut("1000", function() { $(this).attr("src", "anotherImage.png").fadeIn(1000); }); }, function() { $(this).stop().fadeOut("1000", function() { $(this).attr("src", "firstImage.png").fadeIn(1000); }); }); 

在此示例中, #someElement引用img元素。 src属性在hover时更改,具有淡入淡出效果。

编辑 – 重新阅读你的问题,我认为你想要改变background-image CSS属性,而不是img元素的src 。 如果是这种情况,请看一下这个例子 。 所有真正改变的是用css替换jQuery attr函数。

使用以下代码:

 
$(document).ready(function(){ $("#someElement").hover(function() { $(this).stop().fadeOut("1000", function() { $(this).css("background", "url('1.jpg')").fadeIn(1000); }); }, function() { $(this).stop().fadeOut("1000", function() { $(this).css("background", "url('2.jpg')").fadeIn(1000); }); }); });

HTML

这是HTML元素,它将在后台显示图像:

 

CSS

我们定义了两个CSS类。 包含image1.jpg的元素的默认值和包含image2.jpg的第二个类:

 .image { width: 1000px; /* Image width */ height: 500px; /* Image height */ background: url('../images/image1.jpg') no-repeat; /* First image */ -moz-background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%;; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src = "../images/image1.jpg", sizingMethod = 'scale'); background-size: 100% 100%; background-position: center; } .image.image-2 { background: url('../images/image2.jpg') no-repeat; /* Second image */ -moz-background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%;; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src = "../images/image2.jpg", sizingMethod = 'scale'); background-size: 100% 100%; background-position: center; } 

JavaScript的

JavaScript使用回调/承诺来确保每个转换以正确的顺序发生:

 var elem = $('.image'); // Define the element elem.hover(toggleImage); // When hovering over the element, run the toggleImage function function toggleImage() { // Fade out 0.5 secs, toggle image class, fade in 0.5 secs elem.fadeOut(500, function(){ elem.toggleClass('image-2').promise().done(function(){ elem.fadeIn(500); }); }) }