jQuery感知鼠标滑入方向

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

jQuery感知鼠标滑入方向属于前端实例代码,有关更多实例代码大家可以查看

分享一段代码实例,它实现了感知鼠标方位的功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style>
#box {
  width: 200px;
  height: 200px;
  border: 1px solid #999;
  margin: 200px auto;
  position: relative;
  zoom: 1;
  overflow: hidden;
}
#box1 {
  height: 200px;
  background-color: orange;
  text-align: center;
  line-height: 200px;
}
#box2 {
  position: absolute;
  left: -200px;
  top: -200px;
  width: 200px;
  height: 200px;
  background-color: red;
  text-align: center;
  line-height: 200px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function() {
  $("#box").on("mouseenter mouseleave",function(e) {
    var w = $(this).width();
    var h = $(this).height();
    var x=(e.pageX-this.offsetLeft-(w/2))*(w>h?(h/w):1);
    var y=(e.pageY-this.offsetTop-(h/2))*(h>w?(w/h):1);
    var dirNum=Math.round((((Math.atan2(y,x)*(180/Math.PI))+180)/90)+3)%4;
 
    var eventType = e.type;
    var aPos=[{left:0,top:-200},{left:200,top:0},{left:0,top:200},{left:-200,top:0}];
    if(eventType == 'mouseenter'){
      $("#box2").css(aPos[dirNum]).stop(true,true).animate({left:0,top:0},200);
    }else{
      $("#box2").stop(true,true).animate(aPos[dirNum],200);
    }
  });
});
</script>
</head>
<body>
  <div id="box">
    <div id="box1">前端教程网一</div>
    <div id="box2">前端教程网二</div>
  </div>
</body>
</html>

jQuery感知鼠标滑入方向,这样的场景在实际项目中还是用的比较多的,关于jQuery感知鼠标滑入方向就介绍到这了。

回复

我来回复
  • 暂无回复内容