使网页的行为层(JavaScript)和网页的结构层(HTML)完全分离

并做了一些优化和判定,使其支持平稳退化。
前台HTML代码:

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8"/>
  <title>Picture Test</title>
 </head>
 <body>
   <h1>Snapshots</h1>
   <ul id="imagegallery">
    <li>
     <a href="images/fireworks.gif" title="a fireworks display">Fireworks</a>
    </li>
    <li>
     <a href="images/coffee.gif" title="a cup of black display">Coffee</a>
    </li>
    <li>
     <a href="images/rose.gif" title="a red rose display">Rose</a>
    </li>
    <li>
     <a href="images/bigben.gif" title="The famous display">Big Ben</a>
    </li>
   </ul>
   <img id="placeholder" alt="Picture"/>
   <p id="description">Choose an image.</p>
  <script src="scripts/example.js"></script>
 </body>
</html>

在scripts文件夹中的example.js文件中,JavaScript代码:

 

function showPic(whichPic){
  var placeholder = document.getElementById("placeholder");
  if(!placeholder ) return false;
  var source = whichPic.getAttribute("href");
  if(placeholder.nodeName != 'IMG') return false;
  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;
}

function prepareGallery(){ 
  if(!document.getElementsByTagName) return false;
  if(!document.getElementById) return false;
  var gallery = document.getElementById("imagegallery");
  if(!gallery) return false;

  var links = gallery.getElementsByTagName("a");
  for(var i=0; i<links.length; i++){
  links[i].onclick = function(){
  return !showPic(this);
}
}
}

function addLoadEvent(func){
  var oldOnLoad = window.onload;
  if(typeof window.onload != 'function'){
  window.onload = func;
}else{
  window.onload = function(){
  oldOnLoad;
  func;
}
}  
}

addLoadEvent(prepareGallery)

 

posted @ 2013-01-22 15:15  天之涯,海之角  阅读(868)  评论(0编辑  收藏  举报