使用 JavaScript 模拟光标随机移动端
Posted 张驰Zhangchi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 JavaScript 模拟光标随机移动端相关的知识,希望对你有一定的参考价值。
1.效果预览
https://jsfiddle.net/0qmaytco/https://jsfiddle.net/0qmaytco/
2.代码运行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.ghost-user
position: fixed;
left:50%;
top:50%
.ghost-user-flag
background: blue;
width: 2px;
height: 18px;
.ghost-user-name
position: relative;
color: blue;
top:-14px;
font-weight:bold;
</style>
</head>
<body>
<div class="ghost-user" id="target">
<div class="ghost-user-flag">
<div class="ghost-user-name">
Tome
</div>
</div>
<script>
let task = null;
let taskTimer = null
function runTask()
if(!task)
let randomX = Math.random() * 200;
let randomY = Math.random() * 200;
let randomOffsetX = Math.random()*2>=1?1:-1;
let randomOffsetY = Math.random()*2>=1?1:-1;
taskTimer = setInterval(()=>
if(randomX<0 || randomY<0)
clearInterval(taskTimer);
taskTimer = null;
runTask();
return;
newLeft = document.getElementById('target').offsetLeft +randomOffsetX;
newTop = document.getElementById('target').offsetTop +randomOffsetY;
randomX --;
randomY --;
document.getElementById('target').style.left = newLeft +'px';
document.getElementById('target').style.top = newTop +'px';
,1000/60)
runTask();
</script>
</div>
</body>
</html>
以上是关于使用 JavaScript 模拟光标随机移动端的主要内容,如果未能解决你的问题,请参考以下文章