主要内容: @把事件处理函数移出文档 @向后兼容 @确保可访问
1.支持平稳退化吗? 2.它的JavaScript与HTML标记是分离的吗 3.添加事件处理函数 1).检查点 2).变量名里有什么 3).遍历 4).改变行为 5).完成JavaScript函数 4.共享 onload事件 5.优化 6.键盘访问 小心onKeypress 7.把JavaScript与CSS结合起来 8.DOM Core 和 HTML-DOM
最终代码清单: 源代码: <!doctype html> <html> <head> <meta charset="utf-8"> <title>gallery</title> <link rel="stylesheet" href="styles/layout.css" media="screen" />
</head>
<body> <h1>Snapshots</h1> <ul id="imagegallery"> <li> <a href="images/heying.jpg" title="A fireworks display"><img src="images/heying.jpg" alt="Fireworks"/></a> </li> <li> <a href="images/IMG_1984.JPG" title="A cup of black coffee"> <img src="images/IMG_1984.JPG" alt="Coffee"/></a> </li> <li> <a href="images/timg (1).jpg" title="A red, a rose"> <img src="images/timg (1).jpg" alt="Rose"/></a> </li> <li> <a href="images/timg (2).jpg" title="The famous clock"> <img src="images/timg (2).jpg" alt="Big Ben"/></a> </li> </ul>
<img id="placeholder" src="" alt="My Image Gallery"/> <p id="description"> Choose an image </p>
<script type="text/javascript" src="script/showpic_0.js"></script> </body> </html>
@layout.css @charset "utf-8"; /* CSS Document */
body { font-family: "微软雅黑"; color: #333; background-color: #ccc; magin: 1em 10%; } h1{ color:#333; background-color:transparent; } a{ color:#c60; background-color:transparent; font-weight:bold; text-decoration:none; } ul{ padding:0; } li{ float:left; padding:1em; list-style:none; } img{ display:block; clear:both; width:400px; height:400px; }
#imagegallery{ list-style:none; } #imagegallery li{ display:inline; } #imagegallery li a img{ border:0; width:100px; height:100px; } #description{ font-family: "幼圆"; font-size: 24px; font-weight: bold; color: #06C; }
@showpic.js function prepareGallery(){ if(!document.getElementsByTagName)return false; if(!document.getElementById) return false; if(!document.getElementById("imagegallery")) return false; var gallery = document.getElementById("imagegallery"); var links = gallery.getElementsByTagName("a"); for(var i = 0; i < links.length; i++){ links[i].onclick = function(){ return showPic(this) ? false : true; } } } function showPic(whichpic){ if(!document.getElementById("placeholder")) return false; var source = whichpic.getAttribute("href"); var placeholder = document.getElementById("placeholder"); if(placeholder.nodeName != "IMG")return false;//nodeName总是返回一个大写字母的值 placeholder.setAttribute("src",source); if(document.getElementById("description")){ var text = whichpic.getAttribute("title")?whichpic.getAttribute("title"):""; var description = document.getElementById("description"); if(description.firstChild.nodeType == 3){ description.firstChild.nodeValue=text; } } return true; } window.onload = prepareGallery; 小结: @ 尽量让我的JavaScript代码不在依赖于那些没有保证的假设,所以引入了许多项预测和检查。这可以使我的JavaScript代码能够平稳退化0。 @最重要的是把事件处理函数从标记文档分离到了一个外部的JavaScript文件。这使JavaScript代码不再依赖于HTML文档的内容和结构。 结构与行为的分离程度越大越好。
