初次学习这方面,有不足之处请多指教。
做了一个小球碰到墙壁就会反弹,变色的一个小的程序。
关于HTML文件就不做多余的描述,就是一个大盒子里面包含一个小球。
下面着重列举css样式与js代码;
CSS样式:
@charset "utf-8";
body {
margin: 0 auto;
position: relative;
}
.container {
margin:0 auto;
width: 600px;
height: 400px;
position: relative;
border: solid 1px #ccc;
}
.container div {
width: 100px;
height: 100px;
overflow: hidden;
border-radius: 50%;
position: absolute;
}
.container div:nth-child(2) {
background-color: green;
top: 0px;
right: 0px;
}
JS代码:
function main() {
var _lists = document.getElementsByTagName("div")[0].getElementsByTagName("div");
var _timer = 0;
var _height = 400;
var _width = 600;
var _left1 = _width - 100;
var _top1 = 0;
var _h1 = 0, _v1 = 0;
(function move() {
window.clearTimeout(_timer);
if ((_lists[0].offsetLeft - _lists[1].offsetLeft) * (_lists[0].offsetLeft - _lists[1].offsetLeft) + (_lists[0].offsetTop - _lists[1].offsetTop) * (_lists[0].offsetTop - _lists[1].offsetTop) < 10000) {
_h1 = _h1 ? 0 : 1;
}
if (_h1 == 0) {
_left1 -= 10;
if (_left1 <= 0) {
_left1 = 0;
_h1 = 1;
_lists[1].style.background="pink";
}
} else {
_left1 += 10;
if (_left1 >= _width - 100) {
_left1 = _width - 100;
_h1 = 0;
_lists[1].style.background="red";
}
}
if (_v1 == 0) {
_top1 += 5;
if (_top1 >= _height - 100) {
_lists[1].style.background="black";
_top1 = _height - 100;
_v1 = 1;
}
} else {
_top1 -= 5;
if (_top1 <= 0) {
_top1 = 0;
_v1 = 0;
_lists[1].style.background="yellow";
}
}
_lists[1].style.left = _left1 + "px";
_lists[1].style.top = _top1 + "px";
_timer = window.setTimeout(move, 30);
})();
}
window.onload = function () {
main();
}