首页 > 解决方案 > 如何为 HTML 元素的 css 类之一设置超时?

问题描述

我可以设置两个 css 元素类中的一个保持 3 秒的超时吗?如果字段满足条件,则出现第二类元素。但是在应用这个类之前,我想设置一个等待 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>

先感谢您。

标签: javascriptphphtmlcsssettimeout

解决方案


由于您说您不是 javascript 专家并且正在研究 php/html/css,您可以尝试使用CSS 动画属性。请注意,动画通常是一个高级主题。一个更好的解决方案可能是 Mister Jojo 提供的 javascript 解决方案。

我可以理解:

  • 您只能将类放在生成的 html 中
  • 您需要在 3 秒后进行更改
  • 更改必须只发生一次
  • 更改与背景颜色有关

Following there is a possible implementation, based on the previous assumptions.

.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> 


推荐阅读