<!DOCTYPE html>
<html>
<head>
	<meta charset='UTF-8'>
	<title>Div2移动效果</title>
	<style type='text/css'>
		#div1{
			position: absolute;
			top: 10px;
			left: 10px;
			width: 20px;
			height: 20px;
			background-color: black;
			color: white;
			text-align: center;
			line-height: 20px;
			cursor: pointer;
		}
		#div2{
			position: absolute;
			top: 50px;
			left: 50px;
			width: 100px;
			height: 30px;
			background-color: red;
		}
	</style>
</head>
<body>
	<div id='div1'>X</div>
	<div id='div2'></div>
<pre><code>&lt;script type='text/javascript'&gt;
	var div2 = document.getElementById('div2');
	var timer = null;
	var speedX = 5; // 水平速度
	var speedY = 3; // 垂直速度
	var pause = false; // 是否暂停

	function move() {
		if (pause) { // 如果暂停,不执行移动
			return;
		}

		var left = div2.offsetLeft;
		var top = div2.offsetTop;

		// 判断是否碰到浏览器边缘,如果碰到,改变速度方向
		if (left &lt;= 0 || left &gt;= (document.documentElement.clientWidth - div2.offsetWidth)) {
			speedX = -speedX;
		}
		if (top &lt;= 0 || top &gt;= (document.documentElement.clientHeight - div2.offsetHeight)) {
			speedY = -speedY;
		}

		// 移动div2
		div2.style.left = left + speedX + 'px';
		div2.style.top = top + speedY + 'px';
	}

	timer = setInterval(move, 30); // 每30毫秒执行一次移动

	// 点击div1关闭
	document.getElementById('div1').onclick = function() {
		clearInterval(timer); // 清除定时器
		document.body.removeChild(div1); // 移除div1
	}

	// 鼠标移到div2上面,暂停移动
	div2.onmouseover = function() {
		pause = true;
	}

	// 鼠标移出div2,继续移动
	div2.onmouseout = function() {
		pause = false;
	}
&lt;/script&gt;
</code></pre>
</body>
</html>
HTML+JS实现自动反弹的红框效果 - 鼠标悬停暂停

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

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