jquery和css3實現的動態時鐘效果

antzone發表於2017-04-18

本章節分享一段程式碼例項,它利用jQuery和css3實現了動態時鐘效果,

指標在走動的時候有擺動效果,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.wrapper{
  width:200px;
  height:200px;
  background-size:cover;
  border-radius:50%;
  overflow:hidden;
}
.disk{
  background-color:#ccc;
  width:200px;
  height:200px;
  position:relative;
}
.pointer{
  position:absolute;
  top:50%;
  left:50%;
  border-radius:40px;
  transform-origin: bottom center;
  background-color:transparent;
  mix-blend-mode: overlay;
}
.hour-wrapper{
  width:30px;
  height:100px;
  margin:-100px -15px;
}
 
.minute-wrapper{
  width:20px;
  height:100px;
  margin:-100px -10px;
}
.second-wrapper{
  width:10px;
  height:100px;
  margin:-100px -5px;
}
.hour{
  width:24px;
  margin:3px;
  height:94px;
  border-radius:40px;
  background-color:#000;
}
.minute{
  width:14px;
  margin:3px;
  height:94px;
  border-radius:40px;
  background-color:#000;
}
.second{
  width:4px;
  margin:3px;
  height:94px;
  border-radius:40px;
  background-color:#000;
  transform-origin: bottom center;
}
.shakePoint{
  animation:pointShake 0.2s;
}
@keyframes pointShake {
  0%{
    transform:rotate(0deg);
  }
  25%{
    transform:rotate(1deg);
  }
  75%{
    transform:rotate(-1deg);
  }
  100%{
    transform:rotate(0deg);
  }
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(function() {
  var singleDeg = 360 / 60;
 
  function getCurrentTime() {
    var currentTime = new Date();
    return {
      hour: currentTime.getHours() - 12 < 0 ? currentTime.getHours() : currentTime.getHours() - 12,
      minute: currentTime.getMinutes(),
      second: currentTime.getSeconds()
    }
  }
 
  var $pointerHour = $('.hour-wrapper'),
    $pointerMinute = $('.minute-wrapper'),
    $pointerSecond = $('.second-wrapper');
  setInterval(function() {
    var currentTime = getCurrentTime();
    console.log(currentTime);
    $pointerHour.css({
      'transform': 'rotate(' + singleDeg * currentTime.hour * 5 + 'deg)'
    });
    $pointerMinute.css({
      'transform': 'rotate(' + singleDeg * currentTime.minute + 'deg)'
    });
    $pointerSecond.css({
      'transform': 'rotate(' + singleDeg * currentTime.second + 'deg)'
    })
    $('.second').addClass('shakePoint');
  }, 1000);
 
  $('.second').on('webkitAnimationEnd', function() {
    $(this).removeClass('shakePoint');
  })
})
</script>
</head>
<body>
<div class="wrapper">
  <div class="disk">
    <div class="pointer hour-wrapper">
      <div class="hour"></div>
    </div>
    <div class="pointer minute-wrapper">
      <div class="minute"></div>
    </div>
    <div class="pointer second-wrapper">
      <div class="second"></div>
    </div>
  </div>
</div>
</body>
</html>

相關文章