jQuery根据鼠标进入的方位出现动画遮罩效果

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了根据鼠标进入的方位,来决定遮罩层动画的展现效果。

这是一种比较灵活和生动的遮罩层效果,需要的朋友可以做一下参考。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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.pipipi.net" target="_blank">前端教程网</a>
  </div>
</div>
</body>
</html>

回复

我来回复
  • 暂无回复内容