案例

2张图片点击切换

方法一:改变路径

  <img src = 'images/1.jpg' id='img' alt='#' width='100' height='100'>
  <script>
      var oImg = document.getElementById( 'img' );
      var bool = true;  //作用是为了去判断第几张图片
           oImg.onclick = function (){
            oImg.src = 'images/2.jpg';
            boolo = false;
      } else {
            oImg.src = 'images/1.jpg';
            bool = true;
      }
  </script>

注意:如果要定义一个判断变量要用true和false,效率最快;
如果用其他的还要转化成布尔值再来判断;

写成三目:

  oImg.src = 'images/' + (bool?'2':'1') + '.jpg';
  bool = !bool;

注:改变路径是最不推荐的写法,因为src瞬间改变的时候图片是需要加载时间,要是网速不好,可能会出现空档期;


方法二、利用类名来判断:

  <style type="text/css" id= 'hh'>
      *{margin: 0;padding: 0;}
      #box{
          width: 120px;
          height: 120px;
      }
      .box1{
          background:url(images/1.jpg) no-repeat center/cover;
      }
      .box2{
          background:url( 'images/2.jpg' ) no-repeat center/cover;
      }      
  </style>
  </head>
  <body>
      <div id='box' class="box1"> </div>
  <script type="text/javascript">
          var oBox = document.getElementById( 'box' ),
              bool = true;
          oBox.onclick = function () {
              this.className = bool?'box2':'box1';
              bool = ! bool;
           }
  </script>

上面的简写法:直接用布尔值做类名:

  <style type="text/css" id= 'hh'>
      *{margin: 0;padding: 0;}
      #box{
          width: 120px;
          height: 120px;
      }
      .true{
          background:url(images/1.jpg) no-repeat center/cover;
      }
      .false{
          background:url( 'images/2.jpg' ) no-repeat center/cover;
      }      
  </style>
  </head>
  <body>
      <div id='box' class="false"> </div>
  <script type="text/javascript">
          var oBox = document.getElementById( 'box' ),
              bool = true;
          oBox.onclick = function () {
              this.className = bool + '';  //  bool + ''使bool变成字符串'true' 'false'
              bool = ! bool;
           }
  </script>

方法很多 如 利用display: none block 透明度 等等

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 ||| 第二章 使用ArcPy编写脚本 Python支持大部分在其他语言中出现的编程结构。在本章内容中,我们...
    muyan阅读 90,561评论 10 55
  • 多图下载的思路(考虑磁盘缓存) 知识点UITableView展示数据创建模型类描述plist文件加载plist文件...
    JoyceZhao阅读 3,707评论 2 8
  • 一个人一生中都会就固定的模式,而且模式一旦形成,改起来比精卫填海、愚公移山都难。 模式的形成与一个人...
    第九只袜子阅读 1,722评论 0 2
  • 这是燥热的暑假中平凡的一天。嗡嗡的电扇不停地制造着让我安心的噪音,笔记本里还在放着我看了800遍的士兵突击,我靠...
    真的更好吗阅读 1,280评论 0 0
  • 今天把喜宴部的薪酬结构、考核方案重新调整了一下,重新选了部门领导,立马感觉团队战斗力上升了几个量级!一个部门要发展...
    一世惊鸿阅读 37评论 0 0