jQuery根據滑鼠進入的方位出現動畫遮罩效果

antzone發表於2017-04-12

本章節分享一段程式碼例項,它實現了根據滑鼠進入的方位,來決定遮罩層動畫的展現效果。

這是一種比較靈活和生動的遮罩層效果,需要的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
body, a {
  text-align: center;
  color: white;
  text-decoration: none;
}
.hover-slideout {
  display: inline-block;
  margin-top: 10%;
  width: 300px;
  height: 300px;
  background: pink;
  overflow: hidden;
  position: relative;
}
.smelly-cat {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(255,0,0,.5);
  top: -100%;
  left: -100%;
}
h1 {
  font-size: 3em;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function(){
  $('[hover-slideout]').each(function(){
    $(this).hover(function(e){
      $(this).find('[smelly-cat]').css(induction_position($(this), e)).stop(true, true).animate({
        "left":0, 
        "top":0
      }, 200);
    },function(e){
      $(this).find('[smelly-cat]').stop(true, true).animate(induction_position($(this), e), 200);
    });
  });
 
  function induction_position(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:
        obj.left = 0;
        obj.top = "-100%";
        break;
      case 1:
        obj.left = "100%";
        obj.top = 0;
        break;
      case 2:
        obj.left = 0;
        obj.top = "100%";
        break;
      case 3:
        obj.left = "-100%";
        obj.top = 0;
        break;
    }
    return obj;
  }
});
</script>
</head>
<body>
<div class="hover-slideout" hover-slideout>
  <h1>滑鼠從不同方位進入</h1>
  <div class="smelly-cat" smelly-cat>
    <br />
    <br />
    <br />
    <h1>Smelly Cat</h1>
    <br />
    <br />
    <br />
    <br />
    <a href="http://www.softwhy.com" target="_blank">螞蟻部落</a>
  </div>
</div>
</body>
</html>

相關文章