gpt4 book ai didi

javascript - 我怎样才能使带有数字的div改变背景颜色

转载 作者:行者123 更新时间:2023-11-28 15:25:25 26 4
gpt4 key购买 nike

我想知道是否可以按顺序更改带有数字的 div 的背景颜色,以便 1 先行,然后 2 然后 3,并具有自动加载的功能?

这是我目前的代码: 测试

<!--JavaScript for Changing Colours-->
<script type="text/javascript">

</script>

<!--Table Style-->
<style>
body{
background-color: #000000 ;
}
table, th, td {
border: 1px solid #000000 ;
background-color: #000000 ;
}
th,td{
background-color: #303030 !important;
width: 218;
height: 72;
}
#table{
width: 100%;
height: 100%;
}

</style>
</head>


<body>
<!-- Start of Table -->
<table id="table" >
<tr id="first">
<th>&nbsp</th>
<th>&nbsp</th>
<th id="3">&nbsp</th> <!--Change to Blue-->
<th>&nbsp</th>
</tr>
<tr id="second">
<td>&nbsp</td>
<td id="1">&nbsp</td> <!--Change to Yellow-->
<td>&nbsp</td>
<td id="5">&nbsp</td> <!--Change to Orange-->
</tr>
<tr class="third">
<td>&nbsp</td>
<td>&nbsp</td>
<td id="2">&nbsp</td> <!--Change to Green-->
<td>&nbsp</td>
</tr>
<tr id="fourth">
<td id="4">&nbsp</td> <!--Change to White-->
<td>&nbsp</td>
<td>&nbsp</td>
<td>&nbsp</td>
</tr>
</table>

</body>
</html>

最佳答案

你需要setTimeout和一个调用函数并将背景应用于每个单元格的计数器。如果可能,您还应该从 css 中删除 !important,因为这使得覆盖背景颜色变得更加困难 - 它有点老套,应该作为最后的手段使用。

(function() {

var i = 1;
// put colours in an array, we don;t need anything in position 0, because there is no <td id="0">
var colours = [null, 'yellow', 'green', 'blue', 'white', 'orange'];

// the function to set the background
function setColour() {
// reset previous cell if there was one
var previousTd = document.getElementById(i-1);
if(previousTd != null) {
previousTd.style.backgroundColor = '';
}

var td = document.getElementById(i);
if(td != null) {
td.style.backgroundColor = colours[i];
i++;
// wait half a second and call the function again
window.setTimeout(setColour, 500);
}
}

window.addEventListener('load', setColour);

})();

Fiddle

关于javascript - 我怎样才能使带有数字的div改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com