我正在使用简单的 html 和 inlay js + css 创建一个简单的网站,它只跟踪员工是否在工作(通过简单地点击带有他们名字的 td),事情是我从来没有使用过 js 之后阅读文档并查找 stackoverflow 和 w3schools 的一天,我无法运行我的代码。 我的问题是,每当我尝试单击 td 时,背景颜色都不会改变,当我得到解决方案时,整个表格的背景颜色都会改变,但我一次只想要一个 td,有人能帮我吗? 到目前为止我得到了:
<script language=javascript type="text/javascript">
var el
function colCell() {
if (typeof event !== 'undefined')
el = event.srcElement;
elements = document.getElementsByTagName('td');
if (el.style.backgroundColor == "#E5F0F8")
{
el.style.backgroundColor = "#0066bb"
el.style.color ="#ffffff"
}
else if (el.style.backgroundColor == "#0066bb")
{
el.style.backgroundColor = "#ff00ff"
el.style.color = "#ffffff"
}
else
{
el.style.backgroundColor = "#E5F0F8"
el.style.color = "#000000"
}
}
if (window.addEventListener)
window.addEventListener('click', function(e) {
el = e.target
}, true)
</script>
有了这张表:
<div class="contentSection">
<table class="awht2">
<tr>
<td colspan="5" class="line">LCS</td>
</tr>
<tr>
<td onclick="colCell()" style="background-color: #E5F0F8;">
TestFarbe
</td>
考虑 td 和 tr 重复几次。
抱歉这么菜鸟,这是我第一个使用 js 和 html 的元素
最佳答案
一些改进:
<script language=javascript type="text/javascript">
var el
function colCell(el) {
elements = document.getElementsByTagName('td');
if (el.style["background-color"] == "rgb(229, 240, 248)")
{
el.style["background-color"] = "#0066bb"
el.style.color ="#ffffff"
}
else if (el.style["background-color"] == "rgb(0, 102, 187)")
{
el.style["background-color"] = "#ff00ff"
el.style.color = "#ffffff"
}
else
{
el.style["background-color"] = "#E5F0F8"
el.style.color = "#000000"
}
}
/*if (window.addEventListener)
window.addEventListener('click', function(e) {
el = e.target
}, true)*/
</script>
<div class="contentSection">
<table class="awht2">
<tr>
<td colspan="5" class="line">LCS</td>
</tr>
<tr>
<td onclick="colCell(this)" style="background-color: #E5F0F8;">
TestFarbe
</td>
<td onclick="colCell(this)" style="background-color: #E5F0F8;">
TestFarbe2
</td>
<td onclick="colCell(this)" style="background-color: #E5F0F8;">
TestFarbe3
</td>
<td onclick="colCell(this)" style="background-color: #E5F0F8;">
TestFarb4
</td>
<td onclick="colCell(this)" style="background-color: #E5F0F8;">
TestFarbe5
</td>
</tr>
</table>
</div>
你不需要有一个窗口事件,你可以将 this
传递给 function
。
关于Javascript,在单个 td 标签中循环 3 个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54781666/