jquery css3跟隨滑鼠晃動的圖片效果

antzone發表於2017-04-12

本章分享一段程式碼例項,它實現了圖片跟隨滑鼠晃動的效果。

並且圖片上會有光暈出現,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
body {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f0f0f0;
}
.stage {
  position: absolute;
  width: 220px;
  height: 140px;
  top: 50%;
  left: 50%;
  margin: -70px -110px;
  perspective: 600px;
}
.card {
  position: absolute;
  width: 220px;
  height: 140px;
  border-radius: 6px;
  pointer-events: none;
  background-image: url('demo/jQuery/img/Italy.jpg');
  background-size: cover;
  transition: all 0.1s;
  transform-style: preserve-3d;
   -webkit-filter: dorp-shadow();
}
.card .light {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.card .light .lightInset {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  position: absolute;
  top: -100px;
  left: -100px;
  background-image: -webkit-gradient(radial, center center,0, center center,100,from(rgba(255,255,255,0.4)),to(rgba(255,255,255,0)) );
}
.card p {
  width: 100%;
  text-align: center;
  line-height: 140px;
  font-size: 40px;
  transform: translateZ(40px);
  color: #fff;
  position: absolute;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function () {
  var totalDeg = 30;
  var centerPoint = {
    centerX: $('.stage').width() / 2,
    centerY: $('.stage').height() / 2
  }
  $('.stage').on('mousemove touchmove', function (e) {
    var yDeg = (centerPoint.centerX - e.offsetX) * totalDeg / 90;
    var xDeg = -(centerPoint.centerY - e.offsetY) * totalDeg / 90;
    $(this).find('.card').css({
      'transform': ' rotateX(' + xDeg + 'deg) rotateY(' + yDeg + 'deg)'
    })
 
    $(this).find('.lightInset').css({
      'transform': 'translate(' + e.offsetX + 'px,' + e.offsetY + 'px)'
    })
  })
 
  $('.stage').on('mouseleave', function (e) {
    $(this).find('.card').removeAttr('style');
  })
})
</script>
</head>
<body>
  <div class="stage">
    <div class="card">
      <div class="light">
        <div class="lightInset"></div>
      </div>
      <p>螞蟻部落</p>
    </div>
  </div>
</body>
</html>

相關文章