建立基于 DOM 的 Web 应用程序

本文介绍了如何在HTML页面中使用DOM操作实现图片元素的替换,包括原始图片的替换和图片收回到替换过程的简化方法。

我们首先建立一个非常简单的应用程序,然后再添加一点 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的地址即可,简单吧

 

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

转载于:https://www.cnblogs.com/jesse-run/archive/2011/05/26/2059267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值