img标记的宽度错误

wrong width of img tag

本文关键字:错误 img      更新时间:2023-09-26

我试图为我的应用程序构建一个图像上传器。所以我需要调整图像的大小。但我经常在img标记中得到错误的宽度值。不是每次都这样。但有时当我加载图片3次时,或者有时如果我更改图片,就会有旧的宽度。但也不是每次都有。

$(document).on('pageshow', '#profil', function () {
    $('#content').height(getRealContentHeight());
    var max_height = getRealContentHeight();
    var max_width = $(window).width();
    var username = getUrlParameter('user');
    var data;
    var x, y, w, h;
    var preview;
    var reader;
    var pic = document.getElementById('pic');

    var jcrop_api;
    $('#upload').bind("change", function () {
        preview = new Image();
        var file = document.querySelector('input[type=file]').files[0];   
        reader = new FileReader();
        reader.onloadend = function () {
            if (jcrop_api) {
                jcrop_api.setImage(reader.result);
            }
            preview.src = reader.result;
            document.getElementById('pic').src = preview.src;
            alert(pic.height); //there is the false value...sometimes....
            alert(pic.width);
            var size = calculateAspectRatioFit(pic.width, pic.height, max_width, max_height);
            alert("heigth:" + size.height);
            alert("width:" + size.width);
//            document.getElementById('pic').height = size.height;
//            document.getElementById('pic').width = size.width;
            jQuery(function ($) {
                $('#pic').Jcrop({
                    aspectRatio: 1,
                    minSize: [50, 50],
                    maxSize: [300, 300],
                    onChange: showCoords,
                    onSelect: showCoords
                }, function () {
                    jcrop_api = this;
                });
            });
            function showCoords(c) {
                x = c.x;
                y = c.y;
                w = c.w;
                h = c.h;
            };
            function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
                var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
                return {width: srcWidth * ratio, height: srcHeight * ratio};
            }
        };
        if (file) {
            reader.readAsDataURL(file);
        } else {
            preview.src = "";
        }
    });
    $('#continue').bind("click", function () {
       //ajax upload
    });
});

可能是两个问题之一:

1( 你是在css或inline中设置"#pic"元素的高度或宽度尺寸吗?您可能得到的是元素的尺寸,而不是图像的尺寸。

2( 您正在对此img设置"src",但不等待图像加载。你可以试试:

$("#pic").on("load", function() {
    //get dimensions now
});

你必须显示图像吗?否则,您可以使用:将其加载到js中

var img = new Image();

然后使用jQuery加载事件处理程序,如上所述。然后设置:

img.src = 'image url';

您可以尝试以下操作吗:

$("#pic").height();
$("#pic").width();
$("#pic").outerHeight();
$("#pic").outerWidth();

代替:

pic.height
pic.width

看到合适的了吗?