根據滑鼠的方位出現遮罩層效果程式碼例項

antzone發表於2017-04-13

本章節分享一段程式碼例項,它實現了滑鼠懸浮出現這招層效果。

並且這個遮罩層出現和消失的方向與滑鼠移入和移出的方向有關係。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
*{
  margin: 0;
  padding: 0;
  border: 0;
  box-sizing: border-box;
}
.container {
  width: 1200px;
  margin: 0 auto;
  padding: 40px 0px;
}
.box {
  padding: 40px;
}
.iwrap {
  position: relative;
  width: 220px;
  height: 166px;
  margin: 0 auto;
  border: 1px solid #e2e2e2;
  overflow: hidden;
}
.iwrap .float {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #6bc30d;
  padding: 15px;
  top: -100%;
  left: -100%;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function () {
  var iwrap = $(".iwrap");
  var float = $(".float");
 
  iwrap.hover(function (e) {
    float.css(moveForward(iwrap, e)).stop(true, true).animate({ "left": 0, "top": 0 }, 500);
  }, function (e) {
    float.animate(moveForward(iwrap, e), 500);
  });
});
 
var moveForward = function (elem, e) {
  var w = elem.width(), h = elem.height(), direction = 0, obj = {};
  var x = (e.pageX - elem.offset().left - (w / 2)) * (w > h ? (h / w) : 1);
  var y = (e.pageY - elem.offset().top - (h / 2)) * (h > w ? (w / h) : 1);
 
  direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
  switch (direction) {
    case 0://from top
      obj.left = 0;
      obj.top = "-100%";
      break;
    case 1://from right
      obj.left = "100%";
      obj.top = 0;
      break;
    case 2://from bottom
      obj.left = 0;
      obj.top = "100%";
      break;
    case 3://from left
      obj.left = "-100%";
      obj.top = 0;
      break;
  }
  return obj;
}
</script>
</head>
<body>
  <div class="container">
    <div class="box">
      <div class="iwrap">
        <div class="float"></div>
      </div>
    </div>
  </div>
</body>
</html>

相關文章