2012-01-22 67 views
0

我试图编写一些jQuery代码,获取图像在显示之前被克隆和调整大小的组合宽度,问题在于它们之前被添加到DOM的宽度始终为0使用jQuery克隆并调整大小后获取图像的大小

(function($){ 
    var $images = createDiv(), 
     totalWidth = 0; 

    //loop through a list of images 
    $("#images > li > img").each(function(){ 
     var $this = $(this), 
      $img = $this.clone(); //createa duplicate of the images 

     $img.height(100); //resize each duplicate to a set height 

     totalWidth += $img.width(); //always equals zero 

     //this always results in 0 too 
     //totalWidth += $img.get(0).clientWidth; 

     //add the cloned image to the div 
     $images.append($img); 

     //remove full sized image to reattach later 
     $this.remove(); 
    }); 

    $images.hide(); 

    $("body").append($images); 

    $("#show").on('click',function(){ 
     $images.show(); 
    }); 

    function createDiv(){ 
     return $('<div id="imgs"></div>'); 
    } 
}(jQuery)); 

下面是一个完整的例子的小提琴:http://jsfiddle.net/bittersweetryan/9c3SH/2/

我怎样才能得到缩放后的图像的总组合宽度他们被添加到前DOM?

回答

1

您首先需要将图像追加到DOM,因为它具有width属性,因为它是一个未附加的DOM节点,它没有“物理”属性。有了这个说法,我建议如下:

(function($){ 
    var $images = createDiv(), 
     totalWidth = 0; 

    //loop through a list of images 
    $("#images > li > img").each(function(){ 
     var $this = $(this), 
      $img = $this.clone(); //createa duplicate of the images 

     $img.height(100); //resize each duplicate to a set height 

     /* the call to css() is to make sure the created image isn't visible 
      in the window. */ 

     $img.css(
      { 
       'position': 'absolute', 
       'left' : -10000 + 'px', 
      }); 

     /* appending the element to the body */ 

     $img.appendTo($('body')); 

     totalWidth += $img.width(); //always equals zero 
     //this always results in 0 too 
     //totalWidth += $img.get(0).clientWidth; 


     /* just to be sure... */ 

     console.log(totalWidth); 

     /* *moving* the created image from its previous place off-screen, 
      and removing also the 'position: absolute;' so that it's visible */ 
     $img.css({'position' : 'static'}).appendTo($images); 

     //remove full sized image to reattach later 
     $this.remove(); 
    }); 

    $images.hide(); 

    $("body").append($images); 


    $("#show").on('click',function(){ 
     $images.show(); 
    }); 

    function createDiv(){ 
     return $('<div id="imgs"></div>'); 
    } 
}(jQuery)); 

JS Fiddle demo