JavaScript元素抖動效果

admin發表於2018-05-22

分享一段程式碼例項,它實現了div元素的抖動效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
div {
  margin: 0 auto;
  width: 150px;
  height: 100px;
  background: red;
  position: relative;
}
 
@keyframes wobble {
  0%,
  10%,
  20%,
  30%,
  40%,
  50%,
  60%,
  70%,
  80%,
  90%,
  100% {
    transform: translateX(-2%)
  }
  5%,
  15%,
  25%,
  35%,
  45%,
  55%,
  65%,
  75%,
  85%,
  95% {
    transform: translateX(2%)
  }
}
#box1 {
  width:20px;
  height: 20px;
  background-color: pink;
  position: absolute;
  top: 0;
  left: -20px;
}
</style>
<script>
window.onload = function () {
  var box1 = document.getElementById('box1');
  var box = document.getElementById('box');
  var timer = true
  box1.onclick = function () {
    if (timer) {
      box.style.animation = "wobble 0.1s infinite both"
    } else {
      box.style.animation = null;
    }
    timer = !timer;
  }
} 
</script>
</head>
<body>
<div id="box">
  <div id="box1"></div>
</div>
</body>
</html>

相關文章