JavaScript隨滑鼠晃動的div塊程式碼例項

admin發表於2018-05-22

分享一段程式碼例項,他利用js和css3實現了div隨著滑鼠指標晃動的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
#main {
  -webkit-transform-style: preserve-3d;
  -webkit-perspective: 1000px;
  transform-style: preserve-3d;
  perspective: 1000px;
}
#images {
  width: 368px;
  height: 204px;
  margin: 100px auto;
  display: block;
  -webkit-transition: transform .1s ease;
  transition: transform .1s ease;
  background:#ccc;
}
</style>
</head>
<body>
  <div id="main">
    <div id="images"></div>
  </div>
 
</body>
<script>
var image = document.getElementById('images'),
    Width = parseInt(getComputedStyle(image, false).width),
    Height = parseInt(getComputedStyle(image, false).height)
    maxX = 20,
    maxY = 20;
image.onmousemove = function (e) {
  var x = e.clientX - image.offsetLeft,
      y = e.clientY - image.offsetTop,
      Xnub,
      Ynub;
  if (y > Height / 2) {
    Xnub = -maxY * y / Height;
  } else {
    Xnub = maxY * (Height - y) / Height;
  }
  if (x > Width / 2) {
    Ynub = maxX * x / Width;
  } else {
    Ynub = -maxX * (Width - x) / Width;
  }
  image.style.webkitTransform = 'rotateX(' + Xnub + 'deg) rotateY(' + Ynub + 'deg) scale(1.1)';
  image.style.transform = 'rotateX(' + Xnub + 'deg) rotateY(' + Ynub + 'deg) scale(1.1)';
  image.onmouseout = function () {
    image.style.webkitTransform = 'rotateX(0deg) rotateY(0deg) scale(1)';
    image.style.transform = 'rotateX(0deg) rotateY(0deg) scale(1)';
  }
}
</script>
</html>

相關文章