不确定我是否正确这样做.
这是我的.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);
});
Run Code Online (Sandbox Code Playgroud)
我想要做的是将IMG Opacity设置为0(#swapImg),替换它src,然后将其淡入.所以我试图在使用来自的回调中淡化它.attr().
如果我这样做不正确,有人可以解释一个更好的方法吗?我在回调中尝试这样做的原因是我需要fadeTo仅在新图像完全加载后才会发生,否则它会闪现一点点.
我正在使用jQuery 1.4,根据http://jquery14.com/day-01/jquery-14,你可以在.attr()方法中进行回调.
您可以使用如下的load事件执行此操作:
$("#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");
});
Run Code Online (Sandbox Code Playgroud)
fade将在图像加载事件触发后开始.