我知道在jQuery中有一個load()
事件,它在圖像加載完成時觸發。但是如果事件處理程序在圖像加載完成後連接呢?檢查圖像是否加載在jQuery(或普通的JavaScript)
是否有像$('#myimage').isLoaded()
這樣的屬性來檢查圖像是否已經加載?
我知道在jQuery中有一個load()
事件,它在圖像加載完成時觸發。但是如果事件處理程序在圖像加載完成後連接呢?檢查圖像是否加載在jQuery(或普通的JavaScript)
是否有像$('#myimage').isLoaded()
這樣的屬性來檢查圖像是否已經加載?
您可以檢查圖像的complete
屬性。
是否有像
$('#myimage').isLoaded()
這樣的屬性來檢查圖像是否已經加載?
沒有,但是你可以把這樣:)
jQuery.fn.isLoaded = function() {
return this
.filter("img")
.filter(function() { return this.complete; }).length > 0;
};
這如果集合中的所有圖像都被加載產生true
和false
如果一個或多個圖像不是。你可以調整它以適應你的需求。
它有點駭人聽聞,我不確定它會在任何地方工作。 做自己的測試。
$.fn.isLoaded = function(message) {
var $this = $(this);
if($this.height() > 0 && $this.width() > 0){
return true;
}
return false;
};
$('#myimage').isLoaded()
編輯:
這在FF和鉻,
$.fn.isLoaded = function(message) {
var $this = $(this);
$this.hide(); // becaues firefox gives a 24*24 dimension
var w = this[0].width;
var h = this[0].height;
$this.show();
if(w > 0 || h > 0){
return true;
}
return false;
};
console.log($('#myimage').isLoaded());
,但如果你隱藏圖像即給出0的寬度和高度,所以它沒有爲IE。對於ie,你不應該隱藏圖像。
我希望有人可以將這兩個功能結合起來製作一個跨瀏覽器的東西,至少它肯定會幫助某個人。
Plain JS in enough。圖像對象具有完整的屬性。 在此處查看:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_img_complete
我認爲這正是你需要的:[http://stackoverflow.com/a/1257418/235710](http://stackoverflow.com/a/1257418/235710) – 2012-07-07 08:37:13