建立基于 DOM 的 Web 应用程序

我们首先建立一个非常简单的应用程序,然后再添加一点 DOM 魔法

<html>
<head>
  <title>Magic Hat</title>
<script language="javascript">
function showRabbit()
{
   var hatImage=document.getElementById("topHat");
   var newImage=document.createElement("img");
   newImage.setAttribute("src","rabbit-hat.gif");
   var imgParent=hatImage.parentNode;
   imgParent.insertBefore(newImage,hatImage);
   imgParent.removeChild(hatImage);
   }
</script>
</head>

<body>
  <h1 align="center">Welcome to the DOM Magic Shop!</h1>
  <form name="magic-hat" >
   <p align="center">
    <img src="topHat.gif" id="topHat" />
    <br /><br />
    <input id="hocusPocus" type="button" value="Hocus Pocus!" onClick="showRabbit();" />
   </p>
  </form>
</body>
</html>

原始图片

topHat

替换图片:

rabbit-hat

 

更加简单的方法:

    imgParent.insertBefore(newImage,hatImage);
    imgParent.removeChild(hatImage);
    改为:imgParent.replaceChild(newImage,hatImage); 即可

其实第二种方法还不算给力啦!还有一种更加给力方法:

    var newImage=document.createElement("img");
    newImage.setAttribute("src","rabbit-hat.gif");
    var imgParent=hatImage.parentNode;
    imgParent.insertBefore(newImage,hatImage);
    imgParent.removeChild(hatImage);

改为:hatImage.setAttribute("src","rabbit-hat.gif");

解析:图片元素很大程度上是由其 src 属性控制的,改变src的地址即可,简单吧

 

然后把兔子收回去是一样的!好玩吧!

posted @ 2011-05-26 22:22  jesse-win  阅读(311)  评论(0)    收藏  举报