我正在編寫一些Javascript來調(diào)整大圖像的大小,以適合用戶的瀏覽器窗口。(不幸的是,我沒有控制源圖像的大小。)因此,HTML中將包含以下內(nèi)容:<img id="photo" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" />我是否可以確定標(biāo)簽中的src圖像img是否已下載?我需要這樣做,因?yàn)槿绻?(document).ready()在瀏覽器加載圖像之前執(zhí)行該命令,就會(huì)遇到問題。 $("#photo").width()并$("#photo").height()返回占位符的大?。ㄌ娲谋荆?。就我而言,這大約是134 x 20?,F(xiàn)在,我只是在檢查照片的高度是否小于150,并假設(shè)是alt文字。但這是一個(gè)很不錯(cuò)的技巧,如果照片的高度小于150像素(在我的特定情況下不太可能),或者替換文字的高度大于150像素(可能發(fā)生在小的瀏覽器窗口中),它就會(huì)中斷。編輯:對(duì)于任何想要查看代碼的人:$(function(){ var REAL_WIDTH = $("#photo").width(); var REAL_HEIGHT = $("#photo").height(); $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(REAL_HEIGHT < 150) { REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); if(REAL_HEIGHT < 150) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); }});更新:感謝您的建議。如果我為$("#photo").load事件設(shè)置回調(diào),則可能會(huì)引發(fā)該事件,因此我直接在image標(biāo)簽上定義了onLoad事件。作為記錄,下面是我最終使用的代碼:<img id="photo" onload="photoLoaded();" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" />然后在Javascript中://This must be outside $() because it may get called firstvar isPhotoLoaded = false;function photoLoaded(){ isPhotoLoaded = true;}$(function(){ //Hides scrollbars, so we can resize properly. Set with JS instead of // CSS so that page doesn't break with JS disabled. $("body").css("overflow", "hidden"); var REAL_WIDTH = -1; var REAL_HEIGHT = -1; $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(!isPhotoLoaded) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } }});
如何使用Javascript / jQuery確定是否已加載圖像?
ibeautiful
2019-10-26 11:17:14