JS判断鼠标进入或离开容器的方向做出特殊hover效果
无意中在uemo的一个子站点看到一个很动感的hover效果,经过简单分析,想必是通过JS判断鼠标进入方向来实现这个hover效果,使父容器中的子容器通过判断鼠标进入方向,从而使子容器从相同的方向“进入”到父容器中并且从鼠标离开的方向“离开”父容器。下面这一段js代码来源于网络,如果想深入了解代码的意义请跳转
http://sentsin.com/web/112.html
HTML代码部分:
<style> body {margin: 50px;} #wrap {width: 100px; height: 100px; background: #000} #result {wdith: auto; height: auto; line-height: 20px;} </style> <div id="wrap"></div> <div id="result"></div>
以下是js代码,需要jQuery的支持
$("#wrap").bind("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 direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左” var eventType = e.type; var dirName = new Array('上方','右侧','下方','左侧'); if(e.type == 'mouseenter'){ $("#result").html(dirName[direction]+'进入'); }else{ $('#result').html(dirName[direction]+'离开'); } });
上述的代码仅仅只是实现判断鼠标进入和离开的方向,然后我们只需要改动部分的代码就能使其匹配多个元素实现这样的效果。
HTML代码:
<style> html,body{margin:0;padding:0;} #wrap{width:300px;height:200px;background:#33aa00; position: relative; overflow: hidden; margin: 10px; float: left;} .mask {width: 300px;height:200px; background: blue; position: absolute; top:-300px;} </style> <div id="wrap"> <div class="mask"></div> </div> <div id="wrap"> <div class="mask"></div> </div> <div id="wrap"> <div class="mask"></div> </div> <div id="wrap"> <div class="mask"></div> </div> <div id="wrap"> <div class="mask"></div> </div> <div id="wrap"> <div class="mask"></div> </div>
JS代码:
$("div[id=wrap]").bind("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 direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; var eventType = e.type; //我们定义子容器起始的坐标 var startX = 0; var startY = 0; switch(direction) { //当从上方进入时 case 0: startX = 0 //横坐标起始为0,即子容器的left值为0 startY = h*-1;; //而高度等于负的容器高度,即子容器的top为-h break; //右 case 1: startX = w; //子容器的left值即为父容器的宽度 startY = 0; //子容器的top值为0 break; //下 case 2: startX = 0; //子容器的left值即为0 startY = h; //子容器的top值即为父容器的高度 break; //左 case 3: startX = w*-1; //子容器的left值即为父容器的宽度负数 startY = 0; //子容器的top值即为0 break; } if(e.type == 'mouseenter'){ //当鼠标进入时,先将子容器位置重置于startX, startY, 然后通过animate函数实现动画转变 $(this).children(".mask").css({'left':startX, 'top':startY}).stop().animate({'left':0, top:0}, 300); }else{ //当鼠标离开时,子容器从当前位置退出 $(this).children(".mask").stop().animate({'left':startX, 'top':startY}, 300); } });