如何为 HTML 元素的 css 类 之一设置超时?
How to setTimeout for one of css classes of HTML element?
我可以设置保持 3 秒元素的两个 css classes 之一的超时吗?
如果字段满足条件,则出现元素的第二个 class。但在此 class 应用之前,我想设置一个等待 3 秒的计时器。
示例:
<?php
$x = rand(1,3);
?>
<div class="first <?php if($x == 1){ echo"second"};?>"></div>
<div class="first <?php if($x == 2){ echo"second"};?>"></div>
<div class="first <?php if($x == 3){ echo"second"};?>"></div>
<script>
If class second exist
for an element then
remove/hold/pause it for
3 seconds and then run it.
</script>
提前致谢。
说什么...?
const
divEl = document.querySelectorAll('div.first')
, random = Math.floor( Math.random() * divEl.length)
;
divEl[random].classList.add('second')
;
setInterval(_=>
{
divEl[random].classList.toggle('second')
}, 3000);
.first {
width : 4em;
height : 2em;
background : lightskyblue;
margin : .6em 1em;
}
.second {
background : coral;
}
<div class="first"></div>
<div class="first"></div>
<div class="first"></div>
既然你说你不擅长javascript,正在研究php/html/css,你可以试试CSS动画属性。请注意,动画通常是一个高级主题。更好的解决方案可能是 Jojo 先生提供的 javascript 解决方案。
我能理解:
- 您只能将 class 放入结果 html
- 您需要在 3 秒后进行更改
- 更改只能发生一次
- 背景颜色的变化
根据前面的假设,下面有一个可能的实现。
.first {
background-color: lightblue;
}
.second {
animation-delay: 3s;
animation-duration: 1ms;
animation-fill-mode: forwards;
animation-iteration-count: 1;
animation-name: delayChangeColor;
}
@keyframes delayChangeColor {
to {
background-color: red;
}
}
<div class="first">1</div>
<div class="first second">2</div>
<div class="first">3</div>
我可以设置保持 3 秒元素的两个 css classes 之一的超时吗? 如果字段满足条件,则出现元素的第二个 class。但在此 class 应用之前,我想设置一个等待 3 秒的计时器。 示例:
<?php
$x = rand(1,3);
?>
<div class="first <?php if($x == 1){ echo"second"};?>"></div>
<div class="first <?php if($x == 2){ echo"second"};?>"></div>
<div class="first <?php if($x == 3){ echo"second"};?>"></div>
<script>
If class second exist
for an element then
remove/hold/pause it for
3 seconds and then run it.
</script>
提前致谢。
说什么...?
const
divEl = document.querySelectorAll('div.first')
, random = Math.floor( Math.random() * divEl.length)
;
divEl[random].classList.add('second')
;
setInterval(_=>
{
divEl[random].classList.toggle('second')
}, 3000);
.first {
width : 4em;
height : 2em;
background : lightskyblue;
margin : .6em 1em;
}
.second {
background : coral;
}
<div class="first"></div>
<div class="first"></div>
<div class="first"></div>
既然你说你不擅长javascript,正在研究php/html/css,你可以试试CSS动画属性。请注意,动画通常是一个高级主题。更好的解决方案可能是 Jojo 先生提供的 javascript 解决方案。
我能理解:
- 您只能将 class 放入结果 html
- 您需要在 3 秒后进行更改
- 更改只能发生一次
- 背景颜色的变化
根据前面的假设,下面有一个可能的实现。
.first {
background-color: lightblue;
}
.second {
animation-delay: 3s;
animation-duration: 1ms;
animation-fill-mode: forwards;
animation-iteration-count: 1;
animation-name: delayChangeColor;
}
@keyframes delayChangeColor {
to {
background-color: red;
}
}
<div class="first">1</div>
<div class="first second">2</div>
<div class="first">3</div>