帮你改了一下,主要问题是虽然把onclick
事件被赋值两次,后面的绿的覆盖前面的那个,所以只有一个动。onclick
事件不属于这个类的的方法,所以还是放在外面,这个类里面添加start
和pause
方法,在事件处理函数中调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Running Ball</title>
<style type="text/css">
.ball {
position: fixed;
width: 100px;
height: 100px;
border-radius: 50px;
top: 50%;
left: 50%;
}
.ball-blue {
background-color: #60bdff;
}
.ball-green {
background-color: #a5f087;
}
</style>
</head>
<body>
<button id="start">Start</button>
<button id="pause">Pause</button>
<p id="ball1" class="ball ball-blue"></p>
<p id="ball2" class="ball ball-green"></p>
<script type="text/javascript">
(function (w, step, tick) {
function Ball(ball) {
var style = window.getComputedStyle(ball, '');
var clock;
var is_running = false;
var x_direction = 1;
var y_direction = 1;
var max_x = w.innerWidth;
var max_y = w.innerHeight;
var ball_x = ball.clientWidth;
var ball_y = ball.clientHeight;
var th = this;
this.move = function () {
ball.style.left = th.getX(parseInt(style.left));
ball.style.top = th.getY(parseInt(style.top));
};
this.getX = function (x) {
x = parseInt(x);
if (x_direction == 1) {
x -= th.getStep();
if (x <= 0) {
x = 0;
x_direction = 2;
}
} else {
x += th.getStep();
if (x >= max_x - ball_x) {
x = max_x - ball_x;
x_direction = 1;
}
}
return x + "px";
};
this.getY = function (y) {
y = parseInt(y);
if (y_direction == 1) {
y -= th.getStep();
if (y <= 0) {
y = 0;
y_direction = 2;
}
} else {
y += th.getStep();
if (y >= max_y - ball_y) {
y = max_y - ball_y;
y_direction = 1;
}
}
return y + "px";
};
this.getStep = function () {
return step;
};
this.start = function(){
if(!is_running){
clock = setInterval(th.move, tick);
is_running = true;
}
}
this.pause = function(){
w.clearInterval(clock);
is_running = false;
}
this.initBall = function () {
ball.style.left = parseInt(((max_x - ball_x) * Math.random())) + 'px';
ball.style.top = parseInt(((max_y - ball_y) * Math.random())) + 'px';
x_direction = Math.random() > 0.5 ? 1 : 2;
y_direction = Math.random() > 0.5 ? 1 : 2;
}
}
var ball1 = new Ball(document.getElementById("ball1"));
ball1.initBall();
var ball2 = new Ball(document.getElementById("ball2"));
ball2.initBall();
document.getElementById('start').onclick = function start() {
ball1.start();
ball2.start();
};
document.getElementById('pause').onclick = function pause() {
ball1.pause();
ball2.pause();
};
})(window,3,30);
</script>
</body>
</html>