Open david2tdw opened 4 years ago
简易版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>判断鼠标进入方向简易版</title>
<style>
body {
padding: 2em;
text-align: center;
}
.block {
position: relative;
display: inline-block;
overflow: hidden;
width: 10em;
height: 10em;
vertical-align: middle;
transform: translateZ(0);
}
.block_hoverer {
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
opacity: 0;
transition: all 0.3s ease;
transition-property: top, left;
transform: rotate(45deg);
}
.block_hoverer:nth-child(1) {
background: red;
top: -70.7%;
}
.block_hoverer:nth-child(2) {
background: lime;
top: 70.7%;
}
.block_hoverer:nth-child(3) {
background: orange;
left: -70.7%;
}
.block_hoverer:nth-child(4) {
background: blue;
left: 70.7%;
}
.block_hoverer:hover {
opacity: 1;
top: 0;
left: 0;
cursor: pointer;
transform: rotate(0);
z-index: 10;
}
.block_content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
text-align: center;
line-height: 10em;
background: #333;
color: #fff;
}
</style>
</head>
<body>
<p class="text">从不同方向使鼠标指针移过下面的内容</p>
<p>↓</p>
<span>→ </span>
<div class="block">
<div class="block_hoverer">上</div>
<div class="block_hoverer">下</div>
<div class="block_hoverer">左</div>
<div class="block_hoverer">右</div>
<div class="block_content">
Hover me!
</div>
</div>
<span> ←</span>
<p>↑</p>
</body>
</html>
关键点: 利用了伪元素生成了 4 个三角形组成了一个正方形,通过 hover 哪个透明的三角形来判断用户的操作方位。
伪元素实现边界智能判断移动