gpt4 book ai didi

javascript - 盒子移出网格 JavaScript

转载 作者:行者123 更新时间:2023-12-03 00:09:37 31 4
gpt4 key购买 nike

我的网格中有一个黄色框。当单击“向上”按钮时,黄色框将向上移动一框。当黄色盒子到达边缘时如何阻止它?我不希望它脱离网格。

let moveCounter = 0;

var grid = document.getElementById("grid-box");


for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerTwo = [];

while (playerTwo.length < 1) {
var randomIndex = parseInt(99 * Math.random());

if (playerTwo.indexOf(randomIndex) === -1) {
playerTwo.push(randomIndex);

var drawPtwo = document.getElementById('square' + randomIndex);
$(drawPtwo).addClass("p-1")
}
};

$('#button_up').on('click', function() {
moveCounter += 1;

$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10
var idUpMove = 'square' + idMove;
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');

});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}

#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.p-1{
background-color: yellow;
}
<div id="grid-box"></div>

<div class="move">
<button id="button_up">UP</button>
<br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

我是 Javascript/jQuery 新手。任何帮助都感激不尽 !谢谢

最佳答案

let moveCounter = 0;

var grid = document.getElementById("grid-box");


for (var i = 1; i <= 100; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var playerTwo = [];

while (playerTwo.length < 1) {
var randomIndex = parseInt(99 * Math.random());

if (playerTwo.indexOf(randomIndex) === -1) {
playerTwo.push(randomIndex);

var drawPtwo = document.getElementById('square' + randomIndex);
$(drawPtwo).addClass("p-1")
}
};

$('#button_up').on('click', function() {
moveCounter += 1;

$pOne = $('.p-1')
var id = $pOne.attr('id')
var idNumber = +id.slice(6);
var idMove = idNumber - 10;
if(idMove < 0){idMove +=10;}
var idUpMove = 'square' + idMove;
$pOne.removeClass('p-1');
$('#' + idUpMove).addClass('p-1');

});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}

#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.p-1{
background-color: yellow;
}
<div id="grid-box"></div>

<div class="move">
<button id="button_up">UP</button>
<br>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

这里我添加了限制框超出网格的条件

if(idMove < 0){idMove +=10;}

如果可移动位置处于负值,则它会再次初始化其现有位置。

关于javascript - 盒子移出网格 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802204/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com