zoukankan      html  css  js  c++  java
  • if-else案例–开关灯

    首先,创建一个html页面,添加一个div盒子,用css设置相应的样式,用js获取盒子的元素,通过点击事件,设置body的背景颜色,用if..else来判断当什么状态设置相应的颜色,(swith...case同理)
     
    break:跳出当前循环
    continue:结束本次循环
     
    .css
    <style type="text/css">
    *{
    margin: 0;
    padding: 0;
    }
    html,body{
    width:100%;
    height:100%;
    background: white;
    }
    #box{
    width:100px;
    height:100px;
    margin:50px auto;
    background: red;
    text-align: center;
    line-height: 100px;
    color:white;
    cursor: pointer;
    }
    </style>

    .html

    <div id="box">点我啊</div>

    .js

    <script>
    // 操作谁,就要先获取谁
    var oBox = document.getElementById("box");
    // 给oBox这个元素绑定一个点击事件;当点击这个盒子的时候,触发后面的function里面的代码;
    // 获取body 元素:document.body
    console.log(document.body);
    oBox.onclick = function () {
    // 当页面现在是白色时,让它变成黑色,
    // 如果本来就是黑色,让它变成白色;
    // 获取
    //{style:{background:""}}
    var curBg = document.body.style.background;
    console.log(curBg);
    /* if(curBg=="" || curBg=="white"){
    console.log(100);
    document.body.style.background = "black";
    }else if(curBg=="black"){
    console.log(200);
    document.body.style.background = "red";
    }else if(curBg==="red"){
    document.body.style.background = "white";
    }*/
    switch (curBg){
    case "":
    document.body.style.background = "black";
    break;
    case "black":
    console.log("red");
    document.body.style.background = "red";
    break;
    case "red":
    document.body.style.background = "white";
    break;
    case "white":
    document.body.style.background = "";
    break;
    }
    }
    // 黑白
    // 红-->黄色-->蓝色--> 黑色-->红
    // 先用if else 在用switch case;
     
    </script>
     
  • 相关阅读:
    Python流程控制
    Python 迭代器和列表解析
    Python 文件对象
    TF-IDF介绍
    hexo博客更换主题
    学习笔记—MapReduce
    Mac下Anaconda的安装和使用
    Flume的介绍和简单操作
    hexo+github搭建个人博客
    Hbase的安装和基本使用
  • 原文地址:https://www.cnblogs.com/CCxi/p/9464293.html
Copyright © 2011-2022 走看看