我正在使用jQuery创建碰撞检查系统,但它似乎不起作用。有两个按钮。您可以使用右键移动一个按钮。一旦按钮碰撞,其中一个按钮应该改变字体颜色。现在,即使没有触摸另一个按钮,该按钮也会始终改变颜色。如果您在理解我时遇到一些问题,请尝试一下。
谢谢,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>my website</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$(document).keydown(function(event) {
if ( event.which == 39){
$('.button0 input').animate({'left': '+='+Math.cos(0*Math.PI/180) *30+'px','top': '+='+Math.sin(0*Math.PI/180) *30+'px'},30);
};
button0button1();
});
function button0button1(){
var div1=$('.button0 input');
var div2=$('.button1 input');
if ((div1.offset().top+div1.outerHeight(true)) < div2.offset().top || div1.offset().top > (div2.offset().top+div2.outerHeight(true)) || (div1.offset().left+div1.outerWidth(true)) < div2.offset().left || div1.offset().left > (div2.offset().left+div2.outerWidth(true))){
$('.button0 input').css('color', 'rgb(0, 128, 255)');
};
};
});
</script>
<style type="text/css">
.button0 input{
position:fixed;
left:30px;
top:213px;
font-family:MS Shell Dlg 2;
font-size:8px;
font-weight:NORMAL;
}
.button1 input{
position:fixed;
left:185px;
top:217px;
font-family:MS Shell Dlg 2;
font-size:8px;
font-weight:NORMAL;
}
</style>
<body>
<div class="button0"><input type="button" style="width: 73px;height: 67px;" value="Button"/></div>
<div class="button1"><input type="button" style="width: 61px;height: 56px;" value="Button"/></div>
</body>
</html>
答案 0 :(得分:0)
我没有检查所有代码(它的当前形式有点令人费解),但我发现了两个问题:
1)您至少有一个比较运算符错误:(div1.offset().left+div1.outerWidth(true)) < div2.offset().left
,应为>
;
2)由于动画不会立即改变你的组件的位置,你应该调用button0button1
作为动画回调,否则按钮会在动画结束期间/结束时发生碰撞,但是代码会报告他们没有碰撞。
$('.button0 input').animate({...},30,button0button1);
// button0button1(); // Delete/comment this line