我在侧边栏中有一个简单的导航系统,您可以在页面上看到here。
正如您所看到的,当您将鼠标悬停在侧边栏中的一个链接上时,背景图像会发生变化,因为我在CSS中为鼠标悬停设置了不同的背景URL。我正在寻找一种简单的方法来添加过渡效果,以便悬停背景图像淡入淡出。我已经尝试了几种jQuery方法,但都没有成功。我想知道是否有一种方法可以使用jQuery或其他方法将淡入淡出过渡添加到背景网址图像中,或者是否必须使用不同的方法才能获得过渡效果。
谢谢,
尼克
发布于 2011-07-30 20:59:21
如果没有一些说明或一些示例代码,很难说出您正在尝试做什么,但是您正在寻找something like this吗
$("#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属性在悬停时更改,具有淡入淡出效果。
编辑-重读您的问题后,我认为您希望更改background-image CSS属性,而不是img元素的src。如果是这样的话,看看this example吧。真正改变的只是用css替换了jQuery的attr函数。
发布于 2011-07-30 21:26:46
使用以下代码:
<div id="someElement" style="background:url('2.jpg');width:100px;height:100px;">
</div>
$(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);
});
});
});发布于 2014-08-13 22:24:39
HTML
这是HTML元素,它的背景中将包含图像:
<div class="image"></div>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);
});
})
}https://stackoverflow.com/questions/6883222
复制相似问题