Trigger animation on element click in pure CSS

自古美人都是妖i 提交于 2019-12-05 01:14:49

Answering my own question. By abusing the :not pseudo class we can trigger an animation after a onclick happened:

#btn:not(:active) {
    /* now keep red background for 1s */
    transition: background-color 1000ms step-end;
}

#btn:active {
    background: red;
}

You can use CSS3 animations and trigger with the :focus & :active...
Now, you can activate the effect with just pressing the TAB key...

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)

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.

So, the inline JS required is:

<a href="#" id="btn" onclick="this.focus();return false">Click</a>

And the CSS3 code

#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; } }

See a working fiddle update: http://jsfiddle.net/s3G7p/1/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!