<!DOCTYPE html>
<html>
<head>
	<title>HTML+JS 实现动态移动的红色方块,鼠标悬停暂停,点击关闭</title>
	<style>
	#div1 {
		position: fixed;
		top: 10px;
		left: 10px;
		width: 30px;
		height: 30px;
		background-color: blue;
		color: white;
		text-align: center;
		font-size: 20px;
		cursor: pointer;
	}
	#div2 {
		position: absolute;
		width: 100px;
		height: 30px;
		background-color: red;
	}
	</style>
</head>
<body>
	<div id='div1' onclick='closeDiv()'>X</div>
	<div id='div2'></div>
<pre><code>&lt;script&gt;
var div2 = document.getElementById('div2');
var speedX = 5; // 水平移动速度
var speedY = 3; // 垂直移动速度
var timer;

function moveDiv() {
	var x = div2.offsetLeft + speedX;
	var y = div2.offsetTop + speedY;

	// 判断是否碰到浏览器边缘
	if (x &lt; 0 || x + div2.offsetWidth &gt; window.innerWidth) {
		speedX = -speedX;
	}
	if (y &lt; 0 || y + div2.offsetHeight &gt; window.innerHeight) {
		speedY = -speedY;
	}

	div2.style.left = x + 'px';
	div2.style.top = y + 'px';
}

timer = setInterval(moveDiv, 30);

function pauseDiv() {
	clearInterval(timer);
}

function resumeDiv() {
	timer = setInterval(moveDiv, 30);
}

div2.onmouseover = pauseDiv;
div2.onmouseout = resumeDiv;

function closeDiv() {
	document.body.removeChild(div1);
	document.body.removeChild(div2);
	clearInterval(timer);
}
&lt;/script&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/mDdO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录