<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
height: 100%;
}
ul {
list-style: none;
position: relative;
width: 600px;
width: 100%;
}
ul> li {
margin: 50px auto;
position: relative;
width: 300px;
height: 300px;
background-color: black;
overflow: hidden;
}
ul> li .bg {
position: absolute;
width: 300px;
height: 300px;
left: -100%;
top: 0;
background-color: red;
text-align: center;
line-height: 300px;
color: blue;
font-size: 150px;
}
.line {
position: absolute;
width: 50%;
height: 1px;
background: red;
right: 0;
top: 50%;
transition: all .3s;
transform-origin: left;
}
.res {
text-align: center;
}
</style>
</head>
<body>
<ul>
<li>
<div class="bg">
SB
</div>
</li>
</ul>
<div class="res"></div>
<script src="./jquery-3.4.1.min.js"></script>
<script>
$("li").on("mouseenter mouseleave", function(e) {
var $bg = $(this).find('.bg');
var w = this.offsetWidth; //获取元素宽度
var h = this.offsetHeight; //获取元素高度
var toTop = this.getBoundingClientRect().top + document.body.scrollTop; //兼容滚动条
var x = e.pageX - this.getBoundingClientRect().left - w / 2; //获取当前鼠标的x轴位置(相对于这个li的中心点)
var y = e.pageY - toTop - h / 2; 获取当前鼠标的y轴位置(相对于这个li的中心点)
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 res = Math.atan2(y, x) / (Math.PI / 180) + 180;
$('.line').css('transform', 'rotate(' + res + 'deg)');
var dirName = new Array('上方', '右侧', '下方', '左侧');
if(eventType == 'mouseenter') {
$('.res').text(dirName[direction] + '进入');
animationIn(direction, $bg);
} else {
$('.res').text(dirName[direction] + '离开');
animationOut(direction, $bg);
}
});
function animationIn(direction, ele) {
switch(direction) {
case 0:
ele.css({
left: 0,
top: '-100%'
}).animate({
top: 0
}, 300);
break;
case 1:
ele.css({
left: '100%',
top: 0
}).animate({
left: 0
}, 300);
break;
case 2:
ele.css({
left: 0,
top: '100%'
}).animate({
top: 0
}, 300);
break;
case 3:
ele.css({
left: '-100%',
top: 0
}).animate({
left: 0
}, 300);
break;
}
}
function animationOut(direction, ele) {
switch(direction) {
case 0:
ele.animate({
top: '-100%'
}, 300);
break;
case 1:
ele.animate({
left: '100%'
}, 300);
break;
case 2:
ele.animate({
top: '100%'
}, 300);
break;
case 3:
ele.animate({
left: '-100%'
}, 300);
break;
}
}
</script>
</body>
</html>