我有一个(正在缓慢地)为RPi开发的新网站。当我单击任一按钮时,该按钮及其他所有内容均消失,在红色背景中仅由文本替换。我做错了什么?
网页:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Garage Doors</title>
<script src="Scripts/GDScripts.js"></script>
<link rel="stylesheet" href="Styles/GDStyles.css" type="text/css">
</head>
<body>
<div>
<table class="statusBox">
<tbody>
<tr>
<td class="statusBox" id="leftBox">
<button onclick="handleButton(this)" name="buttonLeft" type="button" class="myButton" id="buttonLeft">
Toggle Left Garage Door
</button>
<br>Door is Secure
</td>
<td class="statusBox" id="rightBox">
<button onclick="handleButton(this)" name="buttonRight" class="myButton">
Toggle Right Garage Door
</button>
<br>Door is Secure
</td>
</tr>
</tbody>
</table>
<br>
</div>
</body>
</html>
这是CSS文件:
.myButton {
border: 1px solid #337fed;
padding: 6px 24px;
background-color: #3d94f6;
-moz-border-radius-topleft: 6px;
-moz-border-radius-topright: 6px;
-moz-border-radius-bottomright: 6px;
-moz-border-radius-bottomleft: 6px;
cursor: pointer;
color: #ffffff;
font-family: Arial;
font-size: 19px;
font-weight: bold;
text-decoration: none;
text-shadow: #1570cd 0px 1px 0px;
}
.myButton:hover {
background-color: #1e62d0;
}
.myButton:active {
position: relative;
top: 1px;
}
.statusBox {
border-style: ridge;
border-width: 2pt;
font-family: Arial,Helvetica,sans-serif;
font-size: 11pt;
color: #000066;
background-color: #33ff33;
text-align: center;
}
和Javascript:
function handleButton(element) {
var boxField;
if (element.id == "buttonLeft") {
element.innerHTML="Left Garage Door Toggled";
boxField = document.getElementById('leftBox');
boxField.style.backgroundColor="#f50c18";
boxField.textContent="Door Open!!";
}
else {
element.innerHTML="Right Garage Door Toggled";
boxField = document.getElementById('rightBox');
boxField.style.backgroundColor="#f50c18";
boxField.innerHTML="Door Open!!";
}
}
最佳答案
我假设您希望将文本“ Door is secure”更改为“ Door open”,并且希望背景颜色为红色。
如果该假设正确,那么您的问题是boxField定位到表中的整个列。因此,当您执行boxField.innerHTML="Door Open!!";
时,将替换该列的全部内容。因此,您需要将文本与整个列分开定位。
一种方法是:
在HTML中,对于每扇门,将文本包装在带有ID的p标记中。例如:<p id="textLeft">Door is Secure</p>
然后,在您的buttonHandler()函数中,将boxField.innerHTML="Door Open!!";
更改为textLeft.textContent="Door Open!!";