这篇文章给大家介绍使用JavaScript怎么实现一个跟随鼠标移动的盒子,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
position: absolute;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div>111111111</div>
<script>
var div = document.getElementsByTagName('div')[0];
div.onmousedown = function(e) {
e = window.event || e;
// 鼠标按下 获取鼠标距离页面左侧距离
var x = e.clientX;
// 获取鼠标距离页面上侧距离
var y = e.clientY;
// 元素距离页面左侧距离
var elex = div.offsetLeft;
// 元素距离页面上侧距离
var eley = div.offsetTop;
// 相减得到鼠标距离元素的距离
var X = x - elex;
var Y = y - eley;
console.log(X, Y);
document.onmousemove = function(e) {
e = window.event || e;
// 鼠标移动过程中 获取鼠标距离页面距离
var movex = e.clientX;
var movey = e.clientY;
// 1.左侧边界值
// 元素移动过程中距离页面左侧距离
var leftx = movex - X;
var lefty = movey - Y;
// 1.左侧边界值
if (leftx <= 0) {
leftx = 0;
}
// 2.上侧边界值
if (lefty <= 0) {
lefty = 0
}
// 3.右侧边界值
// 页面可视区宽 -元素宽
var rightx = document.documentElement.clientWidth - div.offsetWidth;
if (leftx >= rightx) {
leftx = rightx
}
// 4.下侧边界值
// 页面可视区高 -元素高
var righty = document.documentElement.clientHeight - div.offsetHeight;
if (lefty >= righty) {
lefty = righty;
}
// 鼠标移动过程中 获取鼠标距离页面距离 - 鼠标距离元素的距离 =元素的left top值
div.style.left = leftx + 'px';
div.style.top = lefty + 'px';
}
// 抬起清除移动事件
document.onmouseup = function() {
document.onmousemove = null;
}
// 阻止默认事件
return false;
}
</script>
</body>
</html>
关于使用JavaScript怎么实现一个跟随鼠标移动的盒子就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。