1

我需要在加载后使用JavaScript定位/调整图像大小。为了保持纵横比不变,我必须知道图像的宽度/高度。我可以使用该.load事件,但这触发得太晚了,使重新定位可见。相反,我使用以下技术。

 var interval = setInterval(function(){
     if ($('img').height()) { //This means we have got height.
          //Code that uses $('img').height().
          clearInterval(interval);
     }
 },10);

这可以确保代码在我有图像的宽度/高度信息时以及在它完全加载之前执行。

但是,现在,我需要为一堆图像(特别是在 jQuery 插件中)执行此操作,问题似乎是第一次clearInterval调用清除了所有间隔,除了第一个之外的所有间隔都img保持不变。

我尝试将$(this)jQuery 对象中的间隔 id 保存为属性($(this).interval = setInterval( ...和 data $(this).data("interval", setInterval( ...

我还尝试先将 id 保存在变量中,然后将其分配给调用$(this).data("interval",interval)的右括号之后setInterval

这样做的正确方法是什么,以便每个间隔都清除自己并且只清除自己?

我的代码的完整列表如下

(function($){
   $.fn.extend({
       centerInParent: function(options) {
           var defaults = {
               mode: "fill", //Fill or fit (not implemented)
               padding: 100
           }
           var options =  $.extend(defaults, options);
           return this.each(function() {
               var o = options;
               $t = $(this)
               $p = $t.parent();
               var interval = setInterval(function(){
                   $t.css({position:"absolute", width:"", height:""})
                   if ($t.height()){
                       parentRatio = $p.innerWidth()/$p.innerHeight();
                       thisRatio = $t.innerWidth()/$t.innerHeight();
                       if (thisRatio > parentRatio) var newWidth = $p.innerWidth() - o.padding; else var newWidth = ($p.innerHeight() - o.padding)*thisRatio;
                       var newHeight = newWidth/thisRatio
                       $t.css({
                           width: newWidth,
                           height:newHeight,
                           marginTop: ($p.innerHeight() - newHeight)/2,
                           marginLeft: ($p.innerWidth() - newWidth)/2
                       })
                       clearInterval($t.data("interval"));
                   }
               }, 10)
               $t.data("interval",interval)
           });
       }
   });
})(jQuery);
4

1 回答 1

1

在我的头顶上:

  • 不应该也不应该$t$p全局变量?即被宣布为

    var $t = $(this),
        $p = t.parent();
    
  • 在我看来,加载图像并等待 10 毫秒计算其大小的方法是危险的:它可能会在不同的浏览器中产生不同的结果

  • 在显示之前更好地预加载图像并计算它们的大小:

    var img = new Image();
    img.src = 'http://your-image-url';
    $(img).load(function(){
        // here, deal with img.width and img.height
        // and then display
    });
    
于 2013-02-13T14:40:19.597 回答