我正在用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>
我还没有检查所有的代码(目前的形式有点复杂),但我发现了两个问题:
1) 您至少有一个比较运算符出错:(div1.offset().left+div1.outerWidth(true)) < div2.offset().left
,应该是>
;
2) 由于animate不会立即更改组件的位置,因此应调用button0button1
作为回调以进行animate,否则按钮将在动画期间/动画结束时发生碰撞,但代码会报告它们没有碰撞。
$('.button0 input').animate({...},30,button0button1);
// button0button1(); // Delete/comment this line