使用JQuery缓慢更改/淡化/动画图像 [英] Slowly change/fade/animate an image changing with JQuery

查看:298
本文介绍了使用JQuery缓慢更改/淡化/动画图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的img,
< img src =one.pngid =oneonMouseOver =animateThis(this)>

当用户将鼠标悬停在使用jQuery时,我想慢慢将此图像src更改为oneHovered.png。哪种jQuery方法最好这样做?我看到很多例子都希望我改变CSS背景。有什么可以直接改变src属性吗?

I want to slowly change this image src to "oneHovered.png" when the user hovers over using jQuery. Which jQuery method is best to do this? A lot of examples I see want me to change the CSS background. Is there anything to alter the src attribute directly?

推荐答案

您可以先淡出图像,然后使用第一个可选参数控制淡出的持续时间。淡出完成后,将触发匿名回调,并将图像的源替换为新的。之后,我们使用另一个持续时间值淡入图像,以毫秒为单位:

You could start by first fading out the image, controlling the duration of the fadeout using the first optional parameter. After the fade out is complete, the anonymous callback will fire, and the source of the image is replaced with the new one. Afterwards, we fade in the image using another duration value, measured in milliseconds:

原始HTML:

<img src="one.png" id="one" />

JavaScript:

JavaScript:

$('#one').hover(function() {

    // increase the 500 to larger values to lengthen the duration of the fadeout 
       // and/or fadein
    $('#one').fadeOut(500, function() {
        $('#one').attr("src","/newImage.png");
        $('#one').fadeIn(500);
    });

});

最后,使用jQuery,动态绑定JavaScript事件要轻松得多,而不使用任何JavaScript属性关于HTML本身。我修改了原来的 img 标签,以便它只有 src id attributes。

Finally, using jQuery, it's much, much easier to bind JavaScript events dynamically, without using any JavaScript attributes on the HTML itself. I modified the original img tag so that it just has the src and id attributes.

jQuery hover 事件将确保当用户使用鼠标悬停在图像上时该函数将触发。

The jQuery hover event will ensure that the function fires when the user hovers over the image with the mouse.

如需更多阅读,另请参阅 jQuery fadeOut jQuery淡入淡出

For more reading, also see jQuery fadeOut and jQuery fadeIn.

图片加载时间可能出现的问题:

如果这是用户第一次悬停在图片上并提出请求,可能会在实际的fadeIn中出现轻微的故障,因为在请求newImage.png时服务器会有延迟。解决方法是预加载此图像。有关预装图像的StackOverflow 的资源有几种。

If it's the first time a user has hovered over an image and making a request for it, there may be a slight glitch in the actual fadeIn, since there will be latency from the server while it's requesting newImage.png. A workaround for this is to preload this image. There are several resources on StackOverflow on preloading images.

这篇关于使用JQuery缓慢更改/淡化/动画图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆