隐藏

图片加载完成事件(jQuery插件)

发布:2020/5/21 11:14:05作者:管理员 来源:本站 浏览次数:986

/**
 * -------------------------------------------------------------
 * 图片加载完成事件
 * -------------------------------------------------------------
 * 必须的JS: jquery.1.4.js
 * -------------------------------------------------------------
 * imgcomplete(callback): 绑定图片加载完成事件
 *     callback(Function): 内容变化事件回调函数
 *         回调函数: function(width, height)
 *         回调参数: width=图片实际宽度, height=实际高度, this=图片
 * -------------------------------------------------------------
 * author: 赵卉华
 * date: 2012-11-13
 * -------------------------------------------------------------
 */
(function($) {
    $.fn.imgcomplete = function(callback) {
        return this.each(function() {
            var self = this,
                $this = $(this);
            if (!$this.is("img")) {
                return true;
            }
            var img = new Image();
            img.src = $this.attr("src");
            if (img.complete) { // 如果图片已经存在于浏览器缓存, 直接回调
                callback.call(self, img.width, img.height);
            } else {
                img.onload = function () { // 经测试IE/FF都支持(测了IE8/FF10)
                    if (!img.complete) return;
                    callback.call(self, img.width, img.height);
                }
            }
            return true;
        });
    };
})(jQuery);
————————————————