<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>判断鼠标进入方向</title>
<style>
html,body{
margin:0;
padding:0;
}
.wrap{
width:300px;
height:300px;
position: relative;
margin:50px;
overflow: hidden;
}
.mask{
width: 100%;
height: 100%;
position: absolute;
top: 100%;
left: 0;
background: black;
opacity: .5;
color: white;
font-size: 30px;
line-height: 300px;
text-align: center;
}
.img{
width: 100%;
height: 100%;
background:#33aa00;
display:inline-block;
font-size:50px;
text-align:center;
line-height:300px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="img">
</div>
<div class="mask">
You are very beautiful!
</div>
</div>
<script src="js/jquery-3.2.0.min.js"></script>
<script>
$(".wrap").bind("mouseenter mouseleave",
function(e) {
var mask = $(this).find('.mask');
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 dirName = new Array('上方','右侧','下方','左侧');
if(e.type == 'mouseenter'){
mouseIN(direction,mask);
}else{
mouseOut(direction,mask);
}
});
function mouseIN(direction,ele) {
switch (direction){
//上方
case 0:
ele.css({
top:"-100%",
left:0
}).animate({
top:0
},500);
break;
//右
case 1:
ele.css({
top:0,
left:'100%'
}).animate({
left:0
},500);
break;
//下
case 2:
ele.css({
top:"100%",
left:0
}).animate({
top:0
},500);
break;
//左
case 3:
ele.css({
top:0,
left:'-100%'
}).animate({
left:0
},500);
break;
}
};
function mouseOut(direction,ele) {
switch (direction){
case 0:
ele.animate({
top:'-100%'
})
break;
case 1:
ele.animate({
left:'100%'
});
break;
case 2:
ele.animate({
top:'100%'
});
break;
case 3:
ele.animate({
left:'-100%'
})
break;
}
}
</script>
</body>
</html>
js判断鼠标移入的方向并触发事件
最新推荐文章于 2025-06-16 23:59:03 发布