<!DOCTYPE html>
<html>
<head>
	<title>JS定时器实时改变DIV2的位置</title>
	<style type="text/css">
		#div1 {
			width: 100%;
			height: 100%;
			background-color: #f0f0f0;
			position: fixed;
			top: 0;
			left: 0;
			z-index: -1;
		}
		#div2 {
			width: 100px;
			height: 30px;
			background-color: red;
			position: absolute;
			top: 0;
			left: 0;
			border-radius: 5px;
			cursor: pointer;
		}
		#close {
			width: 15px;
			height: 15px;
			background-color: #fff;
			position: absolute;
			top: -10px;
			right: -10px;
			border-radius: 50%;
			cursor: pointer;
			text-align: center;
			line-height: 15px;
			font-size: 12px;
			color: #999;
			border: 1px solid #999;
		}
	</style>
</head>
<body>
	<div id="div1"></div>
	<div id="div2">
		<div id="close">X</div>
	</div>
	<script type="text/javascript">
		var div2 = document.getElementById("div2");
		var closeBtn = document.getElementById("close");
		var timer = null;
		var speedX = 5;
		var speedY = 5;
		var posX = 0;
		var posY = 0;
		var timerInterval = 20;
<pre><code>	// 初始化div2的位置
	div2.style.top = posY + &quot;px&quot;;
	div2.style.left = posX + &quot;px&quot;;

	// 关闭按钮的点击事件
	closeBtn.onclick = function() {
		div2.style.display = &quot;none&quot;;
	}

	// 鼠标移入div2暂停定时器
	div2.onmouseover = function() {
		clearInterval(timer);
	}

	// 鼠标移出div2重新启动定时器
	div2.onmouseout = function() {
		timer = setInterval(move, timerInterval);
	}

	// 定时器改变div2的位置
	function move() {
		var clientWidth = document.documentElement.clientWidth;
		var clientHeight = document.documentElement.clientHeight;
		posX += speedX;
		posY += speedY;
		if (posX &lt;= 0) {
			posX = 0;
			speedX = -speedX;
		}
		if (posX + div2.offsetWidth &gt;= clientWidth) {
			posX = clientWidth - div2.offsetWidth;
			speedX = -speedX;
		}
		if (posY &lt;= 0) {
			posY = 0;
			speedY = -speedY;
		}
		if (posY + div2.offsetHeight &gt;= clientHeight) {
			posY = clientHeight - div2.offsetHeight;
			speedY = -speedY;
		}
		div2.style.top = posY + &quot;px&quot;;
		div2.style.left = posX + &quot;px&quot;;
		closeBtn.style.top = -posY - 10 + &quot;px&quot;;
		closeBtn.style.right = -posX - 10 + &quot;px&quot;;
	}

	// 启动定时器
	timer = setInterval(move, timerInterval);
&lt;/script&gt;
</code></pre>
</body>
</html>
帮我写一个通过js定时器实时改变div2的位置大小为100px 30px背景为红底色要达到碰到浏览器边缘就反弹回来鼠标移到div2上面就暂停改变位置div2左上角还有关闭功能这个关闭功能跟随div2移动。都写在一个html里

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

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