1、用原生js來判斷圖片加載,
document.getElementById("img2").onload=function(){}
2、如果用多種圖片,用jquery來判斷呢,應該是這樣吧?
$("").load(function(){...});
中選擇器是圖片的id或class,function裡面的方法就是回調函數,在圖片加載完成後執行,但是我試驗了很多,壓根兒不是那麼回事,正確的解決方法是:
$("#imageId").load(function(){
alert("加載完成!");
});
3、在網上找到一段代碼,寫好的一個
function loadImage(url, callback) {
var img = new Image(); //創建一個Image對象,實現圖片的預下載
img.src = url;
if(img.complete) { // 如果圖片已經存在於浏覽器緩存,直接調用回調函數
callback.call(img);
return; // 直接返回,不用再處理onload事件
}
img.onload = function () { //圖片下載完畢時異步調用callback函數。
callback.call(img);//將回調函數的this替換為Image對象
};
};
callback回調行數,就是判斷圖片加載完成後要運行的函數
4、下面是針對多個image的加載判斷。
var imgdefereds=[];
$('img').each(function(){
var dfd=$.Deferred();
$(this).bind('load',function(){
dfd.resolve();
}).bind('error',function(){
//圖片加載錯誤,加入錯誤處理
// dfd.resolve();
})
if(this.complete) setTimeout(function(){
dfd.resolve();
},1000);
imgdefereds.push(dfd);
})
$.when.apply(null,imgdefereds).done(function(){
callback();
});
使用這種方法就可以避免window.onload的不足,不過代碼稍顯復雜 在性能方面比起window.onload經強很多。
5、最後我寫的一個圖片等比例縮放居中顯示的jquery插件的dome
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>圖片按比例自適應縮放</title>
<script src="jquery.js"></script>
<style>
.cnt {
text-align: center;
width: 500px;
height: 300px;
margin: 0 auto;
border: 1px solid #ddd;
overflow: hidden;
}
</style>
</head>
<body>
<div class="cnt">
<img
src="http://hovertree.com/hvtimg/201601/p3t2ldyr.png"
alt="alipay"/>
</div>
<div class="cnt">
<img
src="http://hovertree.com/hvtimg/201601/lbau8hqb.png"
alt="alipay"/>
</div>
<script>
$.fn.resizeImg = function (opt) {
var imgdefereds = [];
return this.each(function () {
opt = $.extend({
maxWidth: 150,
maxHeight: 200
}, opt);
var $self = $(this);
$self.hide();
var dfd = $.Deferred();
$(this).bind('load', function () {
dfd.resolve();
}).bind('error', function () {
//圖片加載錯誤,加入錯誤處理
// dfd.resolve();
})
if (this.complete) setTimeout(function () {
dfd.resolve();
}, 1000);
imgdefereds.push(dfd);
$.when.apply(null, imgdefereds).done(function () {
var w = $self.outerWidth(),
h = $self.outerHeight();
// 當圖片比預覽區域小時不做任何改變
if (w < opt.maxWidth && h < opt.maxHeight) return;
// 當實際圖片比例大於預覽區域寬高比例時
// 縮放圖片寬度,反之縮放圖片寬度
$self.css('position', 'relative');
if (w / h > opt.maxWidth / opt.maxHeight) {
$self.width(opt.maxWidth);
$self.css('top', (opt.maxHeight - h * opt.maxWidth / w) / 2);
} else {
$self.height(opt.maxHeight);
}
$self.show();
});
});
}
$(document).ready(function () {
$('.cnt img').resizeImg({
maxWidth: 300,
maxHeight: 300
});
});
</script>
</body>
</html>