How do I get actual image width and height using jQuery?

前端 未结 5 1043
情书的邮戳
情书的邮戳 2020-11-30 05:49

On a page I have displayed 100 images, which have the width and height attribute changed. Image id is in a loop.

How do I get the original image size, inside this

5条回答
  •  执笔经年
    2020-11-30 06:34

    I had to perform a similar task with a jQuery plugin I created. It keeps state for an inputs text value, but the principle could easily be used for your width and height.

    I would create a custom object that stores the original object's ID, Width and Height. That object is then put into an array. When required to restore the value simply loop the array of custom objects to match ID and bingo, an object with the original width and height.

    You can check out my plugin's code at www.wduffy.co.uk/jLabel to see how I implemented this. Depending on how many images you are changing the array could become a little on the heavy side though.

    An example might look like

    var states = new Array();
    
    function state($obj) {
    
        // Public Method: equals
        this.equals = function($obj) {
            return $obj.attr('id') == this.id;
        };
    
        // Public Properties
        this.id = $obj.attr('id');
        this.width = $obj.attr('width');
        this.height = $obj.attr('height');
    
    };
    
    function getState($obj) {
        var state; 
    
        $.each(states, function() {
            if (this.equals($obj)) {
                state = this;
                return false; // Stop the jQuery loop running
            };
        });
    
        return state;
    };
    

提交回复
热议问题