javascript動態建立Img-預設圖片
阿新 • • 發佈:2019-01-27
javascript動態建立Img,然後檢查狀態,載入影象失敗時使用預設圖片代替
/*圖片載入外掛*/
$.fn.imagesLoaded = function (ok_handler, error_handler) {
"use strict";
var self = {
blank: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",
ok_handler: ok_handler, error_handler: error_handler
}
$ (this).data("self", self).one("load", function () {
var $img = $(this);
var self = $img.data("self");
if (this.src !== self.blank && undefined !== self.ok_handler )
self.ok_handler.call(this);
$img.removeData("self");
self = null;
}).one ("error", function () {
var $img = $(this);
var self = $img.data("self");
if ( undefined !== self.error_handler )
self.error_handler.call(this);
$img.removeData("self");
self = null;
}).each(function () {
var self = $(this).data("self") ;
// cached images don't fire load sometimes, so we reset src.
if (this.complete || this.complete === undefined) {
var src = this.src;
// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
// data uri bypasses webkit log warning (thx doug jones)
//this.src = '#';
this.src = self.blank;
this.src = src;
}
});
return this;
};
使用方法
var $img = $(pself.doc.createElement("img")).hide()
.attr({ "src": $.getSerUrl("organization_getusersignature&userid=" + encodeURIComponent(args.row.data[0]) + "&v=" + new Date().getTime(), pself.head.gettoken()) })
.imagesLoaded(function () {
var $img = $(this);
var w = $img.width();
var h = $img.height();
if (h > 22) {
var factor = w / h;
$img.css({ "width": 22 * factor, "height": 22 });
}
$img.show();
}, function () {
$(this).show();
});
影象載入失敗時,用預設圖片代替,如下圖