在纯 CSS 中点击元素时触发动画
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18376815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger animation on element click in pure CSS
提问by Jan Jongboom
Let's say I have a simple element:
假设我有一个简单的元素:
<a href="#" id="btn" onclick="return false">Click</a>
Now I can change the look of this element on click via :active
:
现在我可以通过单击更改此元素的外观:active
:
#btn:active {
background: red;
}
What I'd like however is that the element will stay red for about a second after I clicked it without altering the HTML (so no checkbox hack) or javascript. Is there a smart trick that can be abused for this?
然而,我想要的是,在我单击它而不更改 HTML(因此没有复选框 hack)或 javascript 后,该元素将保持红色约一秒钟。有没有可以为此滥用的聪明技巧?
回答by Jan Jongboom
Answering my own question. By abusing the :not
pseudo class we can trigger an animation after a onclick happened:
回答我自己的问题。通过滥用:not
伪类,我们可以在 onclick 发生后触发动画:
#btn:not(:active) {
/* now keep red background for 1s */
transition: background-color 1000ms step-end;
}
#btn:active {
background: red;
}
回答by gmo
You can use CSS3 animations
and trigger with the :focus
& :active
...
Now, you can activate the effect with just pressing the TABkey...
您可以使用&CSS3 animations
触发...
现在,您只需按一下键即可激活效果... :focus
:active
TAB
But if you need to activate it with a mouse click.... and in a a tag
you need to set the focus to the object, so some javascript
is required. (inline in this case)
但是,如果你需要使用激活它mouse click....并在a tag
您需要将焦点设置到对象,所以一些javascript
是必需的。(在这种情况下内联)
If you can use another object, let say an input type="text"
then the focus
it's automaticly set when you do the click
, but in this case the focus
action it's given by the browser.
如果您可以使用另一个对象,比如说 aninput type="text"
那么focus
当您执行 时它会自动设置click
,但在这种情况下,focus
它是由浏览器给出的操作。
So, the inline JS required is:
因此,所需的内联 JS 是:
<a href="#" id="btn" onclick="this.focus();return false">Click</a>
And the CSS3 code
和 CSS3 代码
#btn {
background: yellow;
}
#btn:focus, #btn:active {
-webkit-animation: btn-color 1s forwards linear;
-moz-animation: btn-color 1s forwards linear;
-ms-animation: btn-color 1s forwards linear;
-o-animation: btn-color 1s forwards linear;
animation: btn-color 1s forwards linear;
}
@-webkit-keyframes btn-color { 0% { background: red; } 99% { background: red; } 100% { background: yellow; } }
@-moz-keyframes btn-color { 0% { background: red; } 99% { background: red; } 100% { background: yellow; } }
@-ms-keyframes btn-color { 0% { background: red; } 99% { background: red; } 100% { background: yellow; } }
@-o-keyframes btn-color { 0% { background: red; } 99% { background: red; } 100% { background: yellow; } }
@keyframes btn-color { 0% { background: red; } 99% { background: red; } 100% { background: yellow; } }