【问题标题】:How can I change the background color of table cell (td) using two buttons for different colors?如何使用不同颜色的两个按钮更改表格单元格 (td) 的背景颜色?
【发布时间】:2014-10-25 03:06:38
【问题描述】:

我的 HTML 文件:

<!DOCTYPE html>
<html>
<head>
    <title>Wolf and Rabbit Game</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="wolf&rabbit_game.css">
    <script src="wolf&rabbit_game.js"></script>
</head>
<body>
<table>
    <tr>
        <td id="tableCell"></td>
    </tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColorRed">
<input id="button2" type="button" value="I'm green" onclick="setColorGreen">
</body>
</html>

我的 CSS 文件: 桌子{ 文本对齐:居中; 边距:自动; }

td{
    border: 1px black solid;
    width: 25px;
    height: 25px;
}

#button1,#button2{
    text-align: center;
    margin-top: 20px;
    font-size: 1em;
    font-family: Myriad Pro;
    font-weight: semibold;
    color: white;
    border-radius: 15px;
    padding: 1%;
}

#button1{
    background: red;
}

#button2{
    background: green;
}

body{
    text-align: center;
}

img{
    width: 25px;
    height: auto;
}

我的 JavaScript 文件:

function setColor(){
  if ("#button1").click {
    document.getElementById("#tableCell").style.backgroundColor="red";
  };
  if ("#button2").click {
    document.getElementById("#tableCell").style.backgroundColor="green";
  };
};

【问题讨论】:

  • 解释一下你期望看到什么以及结果是什么会很有用 - 盲目地粘贴大量没有解释的代码并不是很好

标签: javascript html css


【解决方案1】:

检查这个 JS Fiddle

JsFiddle link

不需要在两个不同的按钮上调用两个不同的方法,一个方法来接受颜色参数并更改所需元素的颜色就足够了。

您必须像这样修改您的代码,并确保 javascript 代码位于您的按钮标记之前。

<script>
function setColor(color){  
    document.getElementById("tableCell").style.backgroundColor=color;
};
</script>

<table>
    <tr>
        <td id="tableCell">test</td>
    </tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColor('red')">
<input id="button2" type="button" value="I'm green" onclick="setColor('green')">

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多