憤怒的WebAPI(二)——事件案例
阿新 • • 發佈:2018-12-22
1、開關燈
<button id="btn">關燈</button> <script> // 1 獲取元素 var btn = document.getElementById('btn'); var flag = true; // 2 設定點選事件 btn.onclick = function () { if(flag) { document.body.style.backgroundColor = '#000'; flag = false; btn.innerHTML = '開燈'; } else { document.body.style.backgroundColor = '#fff'; flag = true; btn.innerHTML = '關燈'; } } </script>
2、tab欄
本來是用小栗旬做的,奈何圖片地址弄得我太煩,就改成基佬紫背景色了,就醬。
<style> * { margin: 0; padding: 0; } ul { list-style-type: none; } .box { width: 400px; height: 300px; border: 1px solid #ccc; margin: 100px auto; } .hd { height: 45px; } .hd span { display: inline-block; width: 90px; background-color: pink; line-height: 45px; text-align: center; cursor: pointer; } .hd span.current { background-color: purple; } .bd li { height: 255px; background-color: purple; display: none; padding: 10px; color: white; } .bd li.show { display: block; } </style>
<div class="box"> <div class="hd"> <span class="current">體育</span> <span>娛樂</span> <span>新聞</span> <span>綜合</span> </div> <div class="bd"> <ul> <li class="show">我是體育模組</li> <li>我是娛樂模組</li> <li>我是新聞模組</li> <li>我是綜合模組</li> </ul> </div> </div>
<script>
var sps = document.getElementsByTagName('span');
var lis = document.getElementsByTagName('li');
for (var i = 0; i < sps.length; i++) {
sps[i].index = i;
sps[i].onclick = function () {
// 這個for迴圈是把之前起作用元素的樣式去掉,
for (var i = 0; i < sps.length; i++) {
sps[i].className = "";
lis[i].className = "";
}
this.className = "current";
lis[this.index].className = "show";
}
}
</script>