$(document).ready(function() {
$( function() {
$('#executeButton').click(function() {
test();
});
function coords(dx, dy) {
var cx = document.getElementById('block').style.marginLeft;
var cy = document.getElementById('block').style.marginTop;
cx = parseInt(cx) + 40 * dx;
cy = parseInt(cy) + 40 * dy;
if (cx < 0) cx = 0;
if (cy < 0) cy = 0;
if (cx > 360) cx = 360;
if (cy > 360) cy = 360;
document.getElementById('block').style.marginLeft = cx + 'px';
document.getElementById('block').style.marginTop = cy + 'px';
}
function test(){
move(4);
setTimeout(move, 2000, 4);
placePostion();
setTimeout(move, 4000, 4);
placePostion();
setTimeout(move, 6000, 2);
placePostion();
setTimeout(move, 8000, 2);
placePostion();
}
function move(id) {
if (id == '1') {
coords('0','-1');
} else if (id == '2') {
coords('0','1');
} else if (id == '3') {
coords('-1','0');
} else if (id == '4') {
coords('1','0');
}
}
function placePostion() {
var block = $('#block').position();
var dest = $('#dest').position();
if (block.top == dest.top && block.left == dest.left) {
alert("reached");
}
}
});
});
&#13;
#panel {
width: 100%;
height: 100%;
border-style: solid;
padding-top: 10px;
padding-right: 10px;
padding-bottom: 10px;
padding-left: 10px;
}
#game {
width: 400px;
height: 400px;
background-image: linear-gradient(transparent 39px, #888 39px, transparent 40px), linear-gradient(90deg, transparent 39px, #888 39px, transparent 40px);
background-size: 40px 40px, 40px 40px;
border-style: solid;
float: left;
margin-right: 10px;
}
#block {
width: 40px;
height: 40px;
float: left;
transition: 1s;
background-color: red;
outline: 1px solid;
}
#dest {
width: 40px;
height: 40px;
background-color: blue;
outline: 1px solid;
}
#character {
width: 50px;
height: 50px;
outline: 1px solid;
float: left;
background-color: red;
transition: 1s;
}
&#13;
<html>
<head>
<link rel="stylesheet" href="movefunction.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="movecharacter.js"></script>
</head>
<body>
<button id="executeButton">Execute</button>
<div id="panel">
<div id="game">
<div id="block" style="margin-left: 40px; margin-top: 40px;">
</div>
<div id="dest" style="margin-left: 160px; margin-top: 120px;">
</div>
</div>
</div>
</body>
</html>
&#13;
我添加了代码段。这里当红色区块到达蓝色区块时,它应该说出警报,而目前它的行为就像它们从开始本身一样具有相同的位置。它应该实际上移动,当它到达蓝色块时,只有它应该说达到。对于不同的最终位置,它不应显示任何内容。