我想要从右边开始向左侧弹出div
弹球,但它仍然会回到右侧,我知道有太多类似的问题给出了解决方案对于这个,但他们都实现canvas
这不是我的情况,我正在做的方式似乎对我来说,但就像你可以在现场演示中看到球仍然回到右边,这里是代码:
var speed = 15,
directionTop = 1,
directionLeft = 1;
setInterval(function(){
var ballElement = document.getElementsByClassName('ball')[0],
containerElement = document.getElementsByClassName('mainDiv')[0],
playersTestRebounce = document.getElementsByClassName('player')[0];
if (ballElement) {
var boxLeftPos = ballElement.offsetLeft,
boxRightPos = boxLeftPos + ballElement.offsetWidth,
offsetContainer = containerElement.offsetWidth + 40;
offsetContainerTop = containerElement.offsetTop;
if (boxRightPos > offsetContainer) {
directionTop = 1;
directionLeft = -1;
}
if (boxLeftPos < -40) {
directionTop = 1;
directionLeft = 1;
}
if (ballElement.offsetTop > playersTestRebounce.offsetTop && ballElement.offsetTop < (playersTestRebounce.offsetTop + 70) && ballElement.offsetLeft < (playersTestRebounce.offsetLeft + 12)) {
directionTop = 1;
directionLeft = 1;
}
if (ballElement.offsetTop > 390) {
directionTop = -1;
directionLeft = 1;
}
if (ballElement.offsetTop < 0) {
directionTop = 1;
directionLeft = 1;
}
ballElement.style.left = (boxLeftPos + speed * directionLeft) + 'px';
ballElement.style.top = (ballElement.offsetTop + speed * directionTop) + 'px';
/*cordinators = getPos(ballElement);
console.log("ball X : "+ cordinators.y + " ball Y :" +cordinators.x);*/
/*random = Math.floor((Math.random() * 376) + 6);
if (boxLeftPos < -40 || boxRightPos > offsetContainer) {
ballElement.style.top = random + 'px';
} */
}
}, 100);
答案 0 :(得分:1)
基本弹跳可以缩减为此http://jsfiddle.net/52b261e2/1
if (ballElement.offsetTop > 390 ||ballElement.offsetTop <0) {
directionTop *=-1;
}
if (boxLeftPos <0 ||boxRightPos>600) {
directionLeft *=-1;
}
当你到达底部或顶部时,它在-1中变为1,在-1中变为-1 从左到右也是如此
*编辑忘了更新小提琴