首页 > 解决方案 > 在没有Javascript的情况下单击按钮后运行css函数

问题描述

我需要在单击按钮时开始/停止掷骰子,但我不能使用任何 JavaScript。现在它只是无限运行。仅限 CSS/HTML,谢谢。

<!DOCTYPE html>
 <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
    .dice { /* HTML symbols */
        font-size: 100px;
        font-weight: 800;
    }

    .dice::after {
        content:'';
        animation: rolling 6s linear infinite;
    }

    @keyframes rolling {
        0% {content:'\2680';}
        20% {content:'\2681';}
        40% {content:'\2682';}
        60% {content:'\2683';}
        80% {content:'\2684';}
        100% {content:'\2685';}
    }
</style>
</head>
<body>

<span class="dice"></span>

</body>
</html>

标签: htmlcss

解决方案


您可以隐藏一个复选框并定义一个兄弟选择器来更改animation-play-state

.dice {
  /* HTML symbols */
  font-size: 100px;
  font-weight: 800;
}

.dice::after {
  content: '';
  animation: rolling 6s linear infinite;
}

/* set play state to paused when the checkbox is checked*/
input:checked~.dice::after {
  animation-play-state: paused;
}

input {
  opacity: 0;
  position: absolute;
}

.button {
  background: #0099ff;
  color: white;
  display: inline-block;
  border-radius: 4px;
  font-weight: bold;
  font-family: sans-serif;
  padding: .25em 1em;
}

@keyframes rolling {
  0% {content: '\2680';}
  20% { content: '\2681';}
  40% { content: '\2682'; }
  60% { content: '\2683'; }
  80% { content: '\2684'; }
  100% { content: '\2685'; }
}
<label>
  <input type="checkbox" />
  <span class="dice">
  </span>
  <div class="button">Fake Button</div>
</label>


推荐阅读