jQuery悬停图像更改动画
我有一个带有灰度图像的IMG标签.我挂钩了一个Hover()事件,以便将"src"更改为悬停时的彩色图像,并在鼠标移出时更改为灰度.
I have an IMG tag with a grayscale image. I hooked up a Hover() event in order to change the "src" to a color image on hover, and back to grayscale on mouse-out.
这很好,但是更改是突然的.我想在效果上添加一个淡淡的fadeIn(),以使颜色看起来像是淡入淡出.我写了以下我认为可以但不能奏效的文章. (图像改变,但是效果没有褪色或延迟).我在做什么错了?
This works just fine, however the change is abrupt. I'd like to add a slight fadeIn() to the effect so that the color appears to fadein and fadeout. I wrote the following which I thought would work, but doesn't. (The image changes, but there is no fade or delay to the effect). What am I doing wrong?
$("#showForm").hover(
function () {
$(this).fadeIn('slow', function(){
$(this).attr("src", 'images/AddButtonSmall.gif');
});
},
function () {
$(this).fadeIn('slow', function(){
$(this).attr("src", 'images/AddButtonSmallGray.gif');
});
}
);
以下是几种解决方案.您的代码无效,因为您正在设置会立即更改图像的源.仅加载两个图像,用CSS覆盖它们,然后在将父容器鼠标悬停在上面时,将颜色淡入一个颜色,可能会更容易.或者,您可以交叉淡入淡出
Here are a couple solutions. Your code doesn't work because you are setting the source which changes the image immediately. It's probably easier just to load both images, overlay them with CSS and then fade the color one in out when the parent container is moused over. Alternatively you could cross fade them
css
.fader { display: inline-block; }
.fader img:last-child {
position: absolute;
top: 0;
left: 0;
display: none;
}
html
<div class="fader">
<img src="http://placehold.it/300x300/000fff" />
<img src="http://placehold.it/300x300/fff000" />
</div>
在鼠标悬停时淡入
$('.fader').hover(function() {
$(this).find("img:last").fadeToggle();
});
淡入淡出
$('.fader').hover(function() {
$(this).find("img").fadeToggle();
});