javascript检查图像是否存在 [英] javascript check image existence
问题描述
我正在尝试显示Google地图或图像.所以,我要的是默认情况下我要显示图像,如果图像不存在,请显示谷歌地图.为此,默认情况下,我使用#map_canvas {display:none;}
禁用google maps.然后,我需要一个类似布尔条件的条件,该条件检查图像的存在,然后返回true或false,如果为false,则通过更改display ="block";显示地图.但是,我不能完全做到这一点,请您能帮助我吗?
I am trying to show either google map or image. So, what i want is that for default i want to show the image, if image does not exist, show google map. To do so, as a default I disable google maps with #map_canvas {display:none;}
. Then, I need something like a boolean conditions that checks existence of image then, returns true or false, if it is false, display maps, by changing display="block";. But, I do not how to do that exactly, Can you please help me ?
顺便说一句,两个代码分别可以正常工作.
By the way, two codes separately work fine.
推荐答案
如果图像未加载到#worldMap
中,则要显示#map_canvas
,请使用
To show #map_canvas
if the image does not load into #worldMap
use
var img = document.getElementById("worldMap");
img.src = "http://www.freeworldmaps.net/download/maps/political-world-map-big.gif";
img.onerror = function( ) {
img.style.display = "none";
document.getElementById("map_canvas").style.display = "block";
}
显然,您不必在img标签中指定src属性,而是在页面加载时将其设置为上面的值.
You obviously have to not specify the src attribute in your img tag but set it as above when the page loads.
小提琴 此处
这篇关于javascript检查图像是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!