【发布时间】:2018-09-25 11:40:06
【问题描述】:
我正在用 HTML、CSS、JS 和 PHP 编写一个简单的棋盘。我想将自定义颜色添加到偶数和奇数方块以及自定义尺寸(高度和宽度)。我想这样做,但它不起作用。这是我即将参加的考试的作业,因此将不胜感激。先感谢您。
<html>
<body>
Select first color:
<select id="mySelect" onChange="changeColor(value);">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="orange">Orange</option>
</select>
<br><br>
Select second color:
<select id="mySelect2" onChange="changeColor2(value);">
<option value="white">White</option>
<option value="brown">Brown</option>
<option value="red">Red</option>
<option value="purple">Purple</option>
</select>
<br><br>
Dimensions value:
<input type="number" id="dimensions">
<button type="button" onClick="changeDim">Hajde</button>
<table width="270px" cellspacing="0px" cellpadding="0px" border="1px">
<?php
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0)
{
echo "<td id='even'></td>";
}
else
{
echo "<td id='odd'></td>";
}
}
echo "</tr>";
}
?>
</table>
<script>
function changeColor(color) {
var x = document.getElementById("mySelect").selectedIndex;
document.getElementById("par").style.background = color;
}
function changeColor2(color) {
var x = document.getElementById("mySelect2").selectedIndex;
document.getElementById("par").style.background = color;
}
function changeDim() {
var px = "px";
var dimension = document.getElementById("dimensions").value + px;
document.getElementById("even").style.height = dimension;
document.getElementById("even").style.width = dimension;
document.getElementById("odd").style.height = dimension;
document.getElementById("odd").style.width = dimension;
}
</script>
</body>
</html>
【问题讨论】:
-
您需要更具体地说明它是如何无法按预期工作的。我确实注意到您正在使用
id='even'或奇怪的文档可能每个 id 只有 1 个元素。您可能打算使用class='even'/odd 来应用 css 类 -
好的,我滚动得更远,发现您正在调用
getElementById('even')- 这可能无法按预期工作,因为 id 是唯一的。如果您切换到类,请使用document.getElementsByClassName('even'),但您需要遍历生成的元素集合来修改它们
标签: javascript php html css