开发者

Get Imagesize in jQuery

开发者 https://www.devze.com 2022-12-28 16:23 出处:网络
I want to get the imagesize in jquery, I have this code.It works to the point of alert (v); I wonder what is wrong with the rest when v actually contains a value.

I want to get the imagesize in jquery, I have this code. It works to the point of

alert (v);

I wonder what is wrong with the rest when v actually contains a value.

 var v = $('#xxx input').val();
    alert (v);
    var newImg = new Image();
    newImg.src = v;
    var height = newImg.height;
    var width = newImg.width;
    alert开发者_StackOverflow社区 ('The image size is '+width+'*'+height);

Thanks Jean


Your code to get the image size won't always work. The image loads asynchronously, so the height and width will not be available immediately. You'll need something like the following:

var newImg = new Image();
var height, width;

newImg.onload = function() {
    height = newImg.height;
    width = newImg.width;
    window.alert('The image size is '+width+'*'+height);
};

newImg.src = v;


assuming that #xxx is your input container id, your code should work :

<div id="xxx" align="center">
    <input name="test" value="/images/image1.jpg" />
</div>

Update For Chrome

<script type="text/javascript">
    var newImg = new Image();
    $(function() {
        var v = $('#xxx input').val();
        alert(v);
        newImg.src = v;
        setTimeout(function() {
            var height = newImg.height;
            var width = newImg.width;
            alert ('The image size is '+width+'*'+height);
        }, 1000);
    });
</script>


Are you receiving the correct URL to the image when you alert it?

My first idea would be to change the first line to:

var v = $('#xxx').val();

At the moment, you're selecting input elements inside an element with the ID of "xxx", but you want the element that has the ID "xxx".

Edit: another idea:

var v = $('#xxx input').val();
document.body.appendChild((function() {
    var newImg = document.createElement("img");
    newImg.src = v;
    newImg.id = "newImg";
    return newImg;
})());

var height = $("#newImg").attr("height");
var width = $("#newImg").attr("width");
alert('The image size is '+width+'*'+height);


You need to wait for the image to load!

var v = $('#xxx input').val();
alert (v);
var newImg = new Image();
newImg.onload = function() {
  var height = this.height;
  var width = this.width;
  alert ('The image size is '+width+'*'+height);
}
newImg.src = v;

EDIT: Moved the src assignment to the end.

0

精彩评论

暂无评论...
验证码 换一张
取 消