简体   繁体   中英

jquery fire event when element is shown

I need to fire an event on the following conditions for an image:

1) The image has been loaded (the following function takes care of that) 2) The image is shown. (if the image has not been shown yet, height() and width() return zero, meaning I cannot resize the image.

The main problem here is that my image has been loaded into the child of a hidden div. Since it is a child of the hidden div, change() will not work.

Here is the function I am currently using:

 //Takes the number of pixesl to resize the x-axis of the image to
 $.fn.resizeImage = function(newX) {
    return this.each(function() {
        $this = $(this);
        //The load event is defined via plugin and takes care of the problem of the load event 
        //not firing for elements that have been cached by the browser.
        $this.bind('load', function(){
            var y = $this.height();
            var x = $this.width();

            //return if image does not for some reason
            if(x == 0 || y == 0){return;}

            //alert('y: ' + y + ' x: ' + x);
            var ratio = y / x;
            var newY = Math.floor(newX * ratio);
            $this.height(newY);
            $this.width(newX);
        });
    });
 };

<img> elements have height and width properties that are automatically populated by the browser when it determines the dimensions of an image. .height() and .width() map to the more generic offsetHeight and offsetWidth properties that return 0 when an element is hidden. Accessing the height and width properties directly should allow your code to work correctly:

//Takes the number of pixesl to resize the x-axis of the image to
$.fn.resizeImage = function(newX) {
    return this.each(function() {
        var $this = $(this);
        //The load event is defined via plugin and takes care of the problem of the load event 
        //not firing for elements that have been cached by the browser.
        $this.bind('load', function() {
            var y = this.height;
            var x = this.width;

            //return if image does not for some reason
            if (x == 0 || y == 0) {
                return;
            }

            //alert('y: ' + y + ' x: ' + x);
            var ratio = y / x;
            var newY = Math.floor(newX * ratio);
            $this.height(newY);
            $this.width(newX);
        });
    });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM