CSS代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
/*设置样式*/
#rect{
width: 75px;
height: 75px;
/*设置为圆形*/
border-radius:100%;
background-color: #FF0000;
position: fixed;
}
</style>
<!--引用JS代码-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="rect"></div>
</body>
</html>
JS代码
// JS是弱语言类型,一个变量可以赋任意类型
var rect;
var x=0,y=0,speedX=5,speedY=5;
window.onload = function(){
rect = document.getElementById("rect");
setInterval(moveRect,50);
}
function moveRect(){
x+=speedX;
y+=speedY;
//超出左边距
if(x<0){
speedX = Math.abs(speedX);
}
//超出上边距
if(y<0){
speedY = Math.abs(speedY);
}
// 超出右边距
if(x>window.innerWidth - 75){
speedX = -Math.abs(speedX);
}
//超出下边距
if(y>window.innerHeight - 75){
speedY = -Math.abs(speedY);
}
rect.style.left=x+"px";
rect.style.top=y+"px";
}