html元素方向感知
有时候我们需要获取鼠标从元素的哪个方向进入,从而实现一些效果。例如一些方向感知提示。
有时候也需要知道我们鼠标当前落在元素的哪个象限。来控制元素应该朝向哪个区域拓展。
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素方向感知</title>
</head>
<style>
#canvas {
border: 1px solid black;
}
#content {
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
<body>
<div id="content"></div>
<canvas id="canvas"></canvas>
</body>
<script>
/* 元素方向感知 */
function getDirection($element, event) {
const Rect = $element.getBoundingClientRect();
var w = Rect.width,
h = Rect.height,
x =
(event.pageX - $element.offsetLeft - w / 2) *
(w > h ? h / w : 1),
y = (event.pageY - $element.offsetTop - h / 2) * (h > w ? w / h : 1),
direction =
Math.round((Math.atan2(y, x) * (180 / Math.PI) + 180) / 90 + 3) % 4;
return direction;
}
const obj = {
0: 'top',
1: 'right',
2: 'bottom',
3: 'left'
}
/* div为例 */
var content = document.getElementById('content')
content.addEventListener('mouseenter', function (event) {
console.log('进: ' + obj[getDirection(this, event)]);
})
content.addEventListener('mouseleave', function (event) {
console.log('出: ' + obj[getDirection(this, event)]);
})
const Rect = content.getBoundingClientRect()
content.addEventListener('mousemove', function(e) {
x = e.clientX - this.offsetLeft;
y = e.clientY - this.offsetTop;
if (x > Rect.width / 2) {
direction = 'right';
} else {
direction = 'left';
}
if (y > Rect.height / 2) {
direction += ' down';
} else {
direction += ' up';
}
console.log(direction, 'box');
});
/* canvas为例 */
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 0;
var direction = '';
canvas.width = 400;
canvas.height = 200;
var offsetTop = canvas.offsetTop
var offsetLeft = canvas.offsetLeft
canvas.addEventListener('mouseenter', function (event) {
console.log('进: ' + obj[getDirection(this, event)]);
})
canvas.addEventListener('mouseleave', function (event) {
console.log('出: ' + obj[getDirection(this, event)]);
})
canvas.addEventListener('mousemove', function(e) {
x = e.clientX - offsetLeft;
y = e.clientY - offsetTop;
if (x > canvas.width / 2) {
direction = 'right';
} else {
direction = 'left';
}
if (y > canvas.height / 2) {
direction += ' down';
} else {
direction += ' up';
}
console.log(direction, 'canvas');
});
</script>
</html>
讲此代码创建一个html粘贴进去,用浏览器打开,查看控制台,就可以看到。进,出,以及鼠标落在元素哪个方向。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。