JS-点击按钮实现换肤、以及显示、隐藏效果

1,565 阅读1分钟

先给box设置一些简单的样式实现换肤

 <style>
    #box {
        width: 800px;
        height: 200px;
        margin: auto;
        background: red;
    }
</style>

 <body>
     <div id="box"></div>
     <button id="btn">换肤</button>
 </body>
 <script>
 var btn = document.getElementById('btn')
 var box = document.getElementById('box')//先获取要使用的元素
var flag = true;//创建一个变量赋予初始值为true
btn.onclick = function () {
    flag = !flag; 通过true和false 的来回切换实现点击切换效果
    box.style.background  = flag ? 'red' : 'blue';
}
 </script>

设置box样式,通过display属性来实现显示隐藏的切换

 <style>
    #box {
        width: 800px;
        height: 200px;
        margin: auto;
        background: red;
    }
 </style>

 <body>
     <div id="box"></div>
     <button id="btn">显示隐藏</button>
 </body>
 <script>
    var btn = document.getElementById('btn')
    var box = document.getElementById('box')//先获取要使用的元素
    var flag = true;
    btn.onclick = function () {
    flag = !flag;
    box.style.display = flag ? 'block' : 'none';
} 
  </script>