获取JavaScript中加载的图像宽度

时间:2012-12-07 22:31:17

标签: javascript jquery height width image

我在我的JavaScript代码中添加了一个图片,但想要获得正确的宽度和高度。这可能吗?我的代码如下所示:

$('body').append('<img src="path.jpg" width="'
        + w + '" height="' + h + '" alt="" />');

我知道如何在加载后获取图像宽度,但是我正在加载img并希望直接获得相应的宽度和高度。有什么提示吗?

5 个答案:

答案 0 :(得分:3)

您可以在加载后获取图片的尺寸:

var imageWidth;
var imageHeight;
$('<img>').on('load', function(){ 
    imageWidth = this.width; 
    imageHeight = this.height; 
    $('body').append($(this));
}).attr('src', imageUrl);

答案 1 :(得分:1)

HTML规范建议为height指定width<img>作为可视代理的提示,标记和样式规则混合到构建HTML文档的可视化表示。在CSS框模型中,图像尺寸是内在,即它们隐含在二进制blob中。这意味着浏览器必须等待HTTP响应才能确定图像的大小,以及如何布置和定位兄弟姐妹和父母。在HTML页面中指定尺寸有助于浏览器快速呈现页面,因为它可以在从服务器下载图像之前指定宽度和高度。

此时应该清楚的是,在下载之前无法访问客户端上的图像宽度。当Javascript知道它时,浏览器已经知道了,并且你声明它对你的要求来说太迟了。

因此,提示浏览器的唯一选择是测量服务器端的图像。它可以在每个请求的基础上完成(但这是浪费资源),或者它可以在图像首次上载(然后从数据库中检索)时完成一次,或者最终可以假定为常量,例如如果是个人资料图片,您的服务将始终增长或缩小为大约W x H像素(这可能是配置参数)。

答案 2 :(得分:0)

var image = new Image;
image.src = $('img').prop('src');
alert($(image).prop('height'))

答案 3 :(得分:0)

您可以提前加载图像,而无需立即显示。

var img = document.createElement('img');
img.src = 'your_image.jpg';
var imgHeight = img.height,
    imgWidth = img.width;

现在,您可以随时调用它以及正确的详细信息。

答案 4 :(得分:0)

我决定在wordpress中创建一个新功能,输出图像尺寸,以便我可以使用wordpress检索

function wpsc_the_product_dimensions( $width='', $height='', $product_id='' ) {
    if ( empty( $product_id ) )
        $product_id = get_the_ID();


    $product = get_post( $product_id );

    if ( $product->post_parent > 0 )
        $product_id = $product->post_parent;

    $attached_images = (array)get_posts( array(
                'post_type' => 'attachment',
                'numberposts' => 1,
                'post_status' => null,
                'post_parent' => $product_id,
                'orderby' => 'menu_order',
                'order' => 'ASC'
            ) );


    $post_thumbnail_id = get_post_thumbnail_id( $product_id );

    $image_attributes = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );

    $image_dimensions = 'product-link="'.$image_attributes[0].'" product-width="'.$image_attributes[1].'" product-height="'.$image_attributes[2].'"';

    return $image_dimensions;
}

并将image_dimensions附加到img并使用javascript

检索
w = $(this).attr('product-width');
h = $(this).attr('product-height');
相关问题