繁体   English   中英

使用jQuery克隆图像并调整其大小后获取图像的大小

[英]Getting the size of a image after it is cloned and resized using jQuery

我正在尝试编写一些jQuery代码,以获取在显示之前已克隆并调整大小的图像的组合宽度,问题是在将它们添加到DOM之前,宽度始终为0。

(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之前,如何获得总的合并宽度?

首先,您需要将图像附加到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小提琴演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM