【问题标题】:Perform function in attr() callback?在 attr() 回调中执行函数?
【发布时间】:2010-03-12 20:00:09
【问题描述】:

不确定我这样做是否正确。

这是我的.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,然后将其淡入。所以我试图使用来自 @987654326 的回调将其淡入@。

如果我做错了,有人可以解释一下更好的方法吗?我尝试在回调中执行此操作的原因是,我需要仅在新图像完全加载后才发生 fadeTo,否则它会有点闪烁。

我使用的是 jQuery 1.4,根据http://jquery14.com/day-01/jquery-14 看来您可以在.attr() 方法中进行回调。

【问题讨论】:

  • 在您的#swampImg 回调中,您可以使用$(this) 来引用$('#swapImg')。

标签: jquery callback


【解决方案1】:

你可以用这样的加载事件来做到这一点:

$("#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");
             });

图像加载事件触发后,淡入淡出将开始。

【讨论】:

  • 是的,我运行了您的第一个版本,显然 Chrome 正在缓存它,但它无法正常工作。此版本有效。
  • 请注意,fadeIn() 我相信如果元素有display:none 是设计的,而不仅仅是为了改变不透明度。 FadeTo() 是唯一对我有用的东西。感谢您的帮助!
  • 另外说明:我用的是这段代码,fadeIn的时候有轻微的“闪烁”;删除 each() 部分清除了这一点。
【解决方案2】:
$("#swapImg").css("opacity", 0).attr("src", productImages[swapIMG])
         .on("load",function(){ //fires each time when image loaded
            $(this).fadeIn("slow");
         });

这样也正常。

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多