把时间处理函数移出文档
向后兼容
确保可访问
支持平稳退化
检测对象和方法是否存在
直接上代码 有详细注释:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 5 <title>图片库</title> 6 <style type="text/css"> 7 *{margin:0;padding:0;} 8 body{background:#CCC;margin:1em 10%;} 9 img{width:300px;height:300px;display:block;} 10 ul{overflow:hidden;} 11 li{float:left;list-style:none;padding:0 5px;} 12 </style> 13 </head> 14 <body> 15 16 <h1>photo</h1> 17 <div id="imgBox"> 18 <ul> 19 <li><a href="images/Koala.jpg" title="Koala">Koala</a></li> 20 <li><a href="images/Desert.jpg" title="Desert">Desert</a></li> 21 <li><a href="images/Tulips.jpg" title="Tulips">Tulips</a></li> 22 <li><a href="images/Lighthouse.jpg" title="Lighthouse">Lighthouse</a></li> 23 </ul> 24 25 <img id="placeholder" src="images/Koala.jpg" alt="" /> 26 27 <p id="description">Choose an image.</p> 28 </div> 29 <script type="text/javascript"> 30 31 // window.onload 添加多个事件 32 function addLoadEvent(func) { 33 var oldonload = window.onload; 34 if(typeof oldonload != "function"){ 35 window.onload = func; 36 }else{ 37 window.onload = function(){ 38 oldonload(); 39 func(); 40 } 41 } 42 } 43 44 addLoadEvent(prepareGallery); 45 46 function prepareGallery(){ 47 48 // 检测对象或方法是否存在 49 if(!document.getElementById) return false; 50 if(!document.getElementsByTagName) return false; 51 if(!document.getElementById("imgBox"))return false; 52 var gallery = document.getElementById("imgBox"); 53 links = gallery.getElementsByTagName("a"); 54 for (var i = 0, l = links.length; i < l; i++) { 55 links[i].onclick = function(){ 56 // 巧妙的运用showPic函数的返回值 57 // return showPic(this) ? false : true; 58 return !showPic(this); 59 } 60 //links[i].onkeypress = //links[i].onclick; 61 } 62 } 63 64 function showPic(obj) { 65 // 对象检测 66 if(!document.getElementById("placeholder")) return false; 67 68 /* 69 * 获得当前对象的href值,如安装有本地服务器: 70 * IE6和IE7返回 "http://localhost/images/Koala.jpg" 71 * 标准浏览器返回 "images/Koala.jpg" 72 * 为了然所有浏览器都返回一致的结果,给getAttribute()添加第二个参数为2. 73 * 谨记:getAttribute("href")和getAttribute("href", 2);浏览器兼容性。 74 */ 75 var url = obj.getAttribute("href",2); 76 var place = document.getElementById("placeholder"); 77 place.setAttribute("src", url); 78 79 if(document.getElementById("description")){ 80 var text = obj.getAttribute("title"); 81 var description = document.getElementById("description"); 82 // firstChild必须存在,也就是说 <p id="description">这里必须有内容</p> 下面这行代码才有效。 其实这种情况常用 description.innerHTML = text; 83 description.firstChild.nodeValue = text; 84 } 85 return true; 86 } 87 88 </script> 89 90 </body> 91 </html>