<!DOCTYPE html>
<html>
<head>
	<title>JS定时器实时改变div位置</title>
	<style type="text/css">
		#div1{
			width: 500px;
			height: 500px;
			background-color: #ccc;
			position: relative;
		}
		#div2{
			width: 50px;
			height: 50px;
			background-color: red;
			position: absolute;
			top: 0;
			left: 0;
			cursor: pointer;
		}
	</style>
</head>
<body>
	<div id="div1">
		<div id="div2"></div>
	</div>
	<script type="text/javascript">
		var div2 = document.getElementById("div2");
		var timer = null;
		var speedX = 5;
		var speedY = 5;
		var pause = false;
<pre><code>	// 碰到浏览器边缘就反弹回来
	function move(){
		var x = div2.offsetLeft + speedX;
		var y = div2.offsetTop + speedY;
		if(x &lt; 0){
			x = 0;
			speedX = -speedX;
		}
		if(x &gt; (document.documentElement.clientWidth - div2.offsetWidth)){
			x = document.documentElement.clientWidth - div2.offsetWidth;
			speedX = -speedX;
		}
		if(y &lt; 0){
			y = 0;
			speedY = -speedY;
		}
		if(y &gt; (document.documentElement.clientHeight - div2.offsetHeight)){
			y = document.documentElement.clientHeight - div2.offsetHeight;
			speedY = -speedY;
		}
		div2.style.left = x + &quot;px&quot;;
		div2.style.top = y + &quot;px&quot;;
	}

	// 鼠标移到div2上面就暂停改变位置
	div2.onmouseover = function(){
		pause = true;
		clearInterval(timer);
	}

	// 鼠标移开div2就继续改变位置
	div2.onmouseout = function(){
		pause = false;
		timer = setInterval(function(){
			if(!pause){
				move();
			}
		}, 30);
	}

	// 开始改变位置
	timer = setInterval(function(){
		move();
	}, 30);
&lt;/script&gt;
</code></pre>
</body>
</html>
帮我写一个通过js定时器实时改变div2的位置要达到碰到浏览器边缘就反弹回来鼠标移到div2上面就暂停改变位置

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

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