在 attr() 回调中执行函数? [英] Perform function in attr() callback?
问题描述
不确定我这样做是否正确.
Not sure if I am doing this correctly or not.
这是我的 .js
:
var currentIMG;
$( '.leftMenuProductButton' ).hover(function () {
currentIMG = $("#swapImg").attr("src");
var swapIMG = $(this).next(".menuPopup").attr("id");
$("#swapImg").css("opacity", 0)
.attr("src", productImages[swapIMG], function(){
$("#swapImg").fadeTo("slow", 1);
});
}, function () {
$("#swapImg").stop().attr("src",currentIMG);
});
我想要做的是将 IMG 不透明度设置为 0 (#swapImg
),替换它的 src
,然后将其淡入.所以我试图使用来自 .attr()
的回调将其淡入淡出.
What I am trying to do is Set a IMG Opacity to 0 (#swapImg
), replace it's src
, then fade it back in. So I am trying to fade it back in using a callback from the .attr()
.
如果我做错了,有人可以解释一下更好的方法吗?我尝试在回调中执行此操作的原因是我需要仅在新图像完全加载后才会出现淡入淡出,否则它会有点闪烁.
If I am doing this incorrectly, can someone please explain a better way to do this? The reason I am trying to do it in the callback is that I need the fadeTo to only occur after the new image is fully loaded, otherwise it does a bit of a flash.
我正在使用 jQuery 1.4,并且根据 http://jquery14.com/day-01/jquery-14 看来您可以在 .attr()
方法中进行回调.
I am using jQuery 1.4, and according to http://jquery14.com/day-01/jquery-14 it appears you can do a callback in the .attr()
method.
推荐答案
你可以用这样的加载事件来做到这一点:
You can do this with the load event like this:
$("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG])
.one("load",function(){ //fires (only once) when loaded
$(this).fadeIn("slow");
}).each(function(){
if(this.complete) //trigger load if cached in certain browsers
$(this).trigger("load");
});
淡入淡出将在图像加载事件触发后开始.
The fade will start after the image load event fires.
这篇关于在 attr() 回调中执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!