今天,我正在开发一款名为Tic Tac Toe
的游戏,我在其中使用了以下代码:
let init = () => {
const [...boxes] = document.getElementsByClassName('col');
let insert = (box, oper) => {
box.innerHTML = 'X';
};
boxes.forEach(box => {
box.addEventListener('click', event => {
insert(event.target, 1);
});
box.innerHTML = '';
});
};
window.onload = init();

* {
box-sizing: border-box;
margin: 0;
}
.ctn {
height: 300px;
font-size: 0;
padding: 7vh 0;
}
.row {
position: relative;
left: 50vw;
transform: translate(-50%, 0);
width: 300px;
height: 100px;
box-shadow: 0 0 1px #000;
}
.col {
padding: 0;
font: 800 64pt normal;
width: 100px;
height: 100px;
display: inline-block;
box-shadow: 0 0 1px #000;
text-align: center;
}

<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<div class='ctn'>
<div class='row'>
<p class='col'></p>
<p class='col'>D</p>
<p class='col'></p>
</div>
<div class='row'>
<p class='col'></p>
<p class='col'></p>
<p class='col'></p>
</div>
<div class='row'>
<p class='col'></p>
<p class='col'></p>
<p class='col'></p>
</div>
</div>
<script type="text/javascript" src='./script.js'></script>
</body>
</html>
&#13;
如您所见,我在每个方框中添加了Event Listener
。但是,当我实际点击该框时,框会向下翻转。此外,当我点击同一行的所有三个框时,它们实际上会转换为初始位置!
我做错了什么?
答案 0 :(得分:3)
由于您使用inline-block
- 将vertical-align: middle;
添加到col
:
let init = () => {
const [...boxes] = document.getElementsByClassName('col');
let insert = (box, oper) => {
box.innerHTML = 'X';
};
boxes.forEach(box => {
box.addEventListener('click', event => {
insert(event.target, 1);
});
box.innerHTML = '';
});
};
window.onload = init();
* {
box-sizing: border-box;
margin: 0;
}
.ctn {
height: 300px;
font-size: 0;
padding: 7vh 0;
}
.row {
position: relative;
left: 50vw;
transform: translate(-50%, 0);
width: 300px;
height: 100px;
box-shadow: 0 0 1px #000;
}
.col {
padding: 0;
font: 800 64pt normal;
width: 100px;
height: 100px;
display: inline-block;
box-shadow: 0 0 1px #000;
text-align: center;
vertical-align: middle;
}
<div class='ctn'>
<div class='row'>
<p class='col'></p>
<p class='col'>D</p>
<p class='col'></p>
</div>
<div class='row'>
<p class='col'></p>
<p class='col'></p>
<p class='col'></p>
</div>
<div class='row'>
<p class='col'></p>
<p class='col'></p>
<p class='col'></p>
</div>
</div>
PS:我建议您使用flex
或grid
进行此类布局。