JavaScript元素點選背景顏色切換

admin發表於2017-04-14

本章節分享一段程式碼例項,它實現了點選元素實現背景切換效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
body {
  background: #F6F6F6;
}
div {
  width: 220px;
  border: 1px solid #e6e6e6;
  height: 220px;
  background: gray;
  display: table;
  border-radius: 50%;
  margin: 0 auto;
}
div:hover {
  cursor: pointer;
}
</style>
<script>
window.onload=function(){
  var isOpen = false;
  var light = document.querySelector('#light');
  light.onclick = function () {
    if (!isOpen) {
      this.style.background = 'yellow';
    } else {
      this.style.background = 'gray';
    }
    isOpen = !isOpen;
  };
}
</script>
</head>
<body>
<section>
<div id="light"></div>
</section>
</body>
</html>

相關文章