下面是我写的纯代码,有注释,可以直接在Google上面运行
CSS部分:
body{
position: relative;
}
.box{
position: absolute;
}
.b1{
width: 100px;
height: 100px;
border-radius: 100px;
background: green;
left: 100px;
top: 100px;
}
.b2{
width: 100px;
height: 100px;
border-radius: 150px;
background: green;
top: 500px;
left: 500px;
}
JS部分:
var boxs = document.getElementsByClassName('box'); // 因为小球可以有多个,所以获取的是它的父级数组
for (var i = 0; i < boxs.length; i++) {
boxs[i].onmouseup = boxUp;
boxs[i].onmousedown = boxDown;
boxs[i].onmousemove = boxMove;
}
var moveFlag = false; //小球初始状态是静止的
var offsetLeft= 0; //小球初始位置距离浏览器左边的偏移量
var offsetTop = 0; //小球初始位置距离浏览器上边的偏移量
//鼠标的按下事件
function boxDown(event) {
event = event || window.event; // IE浏览器
console.log(event);
moveFlag = true;
offsetLeft = event.clientX - this.offsetLeft;
offsetTop = event.clientY - this.offsetTop;
// this.style.boxShadow = '3px 3px 10px gray';
}
//鼠标抬起事件
function boxUp(event) {
event = event || window.event;
moveFlag = false;
}
//小球的移动事件
function boxMove(event) {
event = event || window.event;
if (moveFlag) {
this.style.left = event.clientX - offsetLeft + 'px';
this.style.top = event.clientY - offsetTop + 'px';
}
for (var i = 0; i < boxs.length; i++) {
if (this == boxs[i]) {
continue;
}
//计算两个小球的圆心距
var distanceX = this.offsetLeft + this.offsetWidth / 2 - (boxs[i].offsetLeft + boxs[i].offsetWidth / 2);
var distanceY = this.offsetTop + this.offsetTop / 2 - (boxs[i].offsetTop + boxs[i].offsetTop / 2);
var distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY)
if (distance <= (this.offsetWidth + boxs[i].offsetWidth) / 2) {
boxs[i].style.background = 'red'; //如果碰撞小球的背景色发生变化
}else {
boxs[i].style.background = 'green';
}
}
}
时候不早了,大家要早睡
网友评论