javascript - jQuery/javascript - 加载前获取图像大小

标签 javascript jquery

我有一个图像列表,在上传后呈现为缩略图。我遇到的问题是我需要完整上传图片的尺寸,以便在尺寸不正确时我可以运行调整大小功能。

构建图像列表的函数

function buildEditList(json, galleryID)
{
    //Hide the list
    $sortable = $('#sortable');
    $sortable.hide();

    for(i = 0, j = json.revision_images.length; i < j; i++) {
        $sortable.append(
            "<li id='image_" + json.revision_images[i].id + "'><a class=\"ui-lightbox\" href=\"../data/gallery/"
            + galleryID
            + "/images/album/"
            + json.revision_images[i].OrgImageName
            + "\"><img id=\""
            + json.revision_images[i].id
            + "\" alt=\"\" src=\"../data/gallery/"
            + galleryID 
            + "/images/album/" 
            + json.revision_images[i].OrgImageName 
            + "\"/></a></li>"
        ).hide();
    }
    //Set first and last li to 50% so that it fits the format
    $('#sortable li img').first().css('width','50%');
    $('#sortable li img').last().css('width', '50%');

    //Fade images back in 
    $sortable.fadeIn("fast",function(){
        var img = $("#703504"); // Get my img elem -- hard coded at the moment
        var pic_real_width, pic_real_height;
        $("<img/>") // Make in memory copy of image to avoid css issues
            .attr("src", $(img).attr("src"))
            .load(function() {
                pic_real_width = this.width;   // Note: $(this).width() will not
                pic_real_height = this.height; // work for in memory images.
        });
        alert(pic_real_height);
    });

}

我一直在尝试使用这个 stackoverflow 中的解决方案发布,但还没有让它工作,或者它可能只是我的代码。如果您对此有任何想法,我可以使用帮助。目前警报返回未定义。

最佳答案

有一个名为 naturalHeight 或 naturalWidth 的新 js 方法将返回您要查找的信息。不幸的是,它不能在旧的 IE 版本中工作。这是我几个月前创建的一个功能,可能对您有用。我在下面添加了一些您的代码作为示例:

function getNatural($mainImage) {
    var mainImage = $mainImage[0],
        d = {};

    if (mainImage.naturalWidth === undefined) {
        var i = new Image();
        i.src = mainImage.src;
        d.oWidth = i.width;
        d.oHeight = i.height;
    } else {
        d.oWidth = mainImage.naturalWidth;
        d.oHeight = mainImage.naturalHeight;
    }
    return d;
}

var img = $("#703504");
var naturalDimension = getNatural(img);
alert(naturalDimension.oWidth, naturalDimension.oHeight)​

关于javascript - jQuery/javascript - 加载前获取图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13850867/

相关文章:

javascript - 使用 jQuery,如何存储调用 $.ajax 函数的结果以供重复使用?

jquery - 选择所有具有文本类型的输入元素,具有匹配的数据属性值

jquery - 水平滑入(从左到右)

javascript - JQuery on ('click' )直接调用函数,而不是在事件监听器中定义它

javascript - 如何通过每次点击选择数组的新索引

javascript - JSDoc : Define allowed values of parameter which has string type

javascript - 如何使用 WebdriverIO 返回一个新的有效页面对象?

javascript - 在 javascript : error - cannot read property of undefined 中学习 OO

javascript - 通过 Ajax 或 Javascript 强制下载文件

jquery - 使用动画循环遍历数组