使用CSS和Javascript(最好不是jQuery,因为我也不了解)如何设置CSS动画,以便当用户触发从暂停状态到播放状态单击文本链接(href)而不是按钮?
答案 0 :(得分:3)
很简单。最初只需将animation-play-state
设置为paused
,然后添加一个类,在单击锚链接时将animation-play-state
设置为running
。
向事件处理程序添加return false
以防止发生锚的默认操作。
window.onload = function() {
var els = document.getElementsByClassName("play-link");
for (var i = 0; i < els.length; i++) {
els[i].addEventListener('click', function(e) {
e.target.previousElementSibling.classList.add('play');
return false;
});
}
}
div {
animation: shake 1s infinite;
animation-play-state: paused;
border: 1px solid;
width: 200px;
height: 100px;
}
@keyframes shake {
from {
transform: translateX(0px);
}
to {
transform: translateX(200px);
}
}
div.play {
animation-play-state: running;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Play</a>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Play</a>
您甚至可以通过打开和关闭paused
课程来切换running
和play
州。
window.onload = function() {
var els = document.getElementsByClassName("play-link");
for (var i = 0; i < els.length; i++) {
els[i].addEventListener('click', function(e) {
e.target.previousElementSibling.classList.toggle('play');
return false;
});
}
}
div {
animation: shake 4s infinite;
animation-play-state: paused;
border: 1px solid;
width: 200px;
height: 100px;
}
@keyframes shake {
0% {
transform: translateX(0px);
}
50% {
transform: translateX(400px);
}
100% {
transform: translateX(0px);
}
}
div.play {
animation-play-state: running;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Toggle Play State</a>
<div class='animate'>Some text</div>
<a href='#' class='play-link'>Toggle Play State</a>