This question already has answers here:
How to have CSS animation only on click and not on page load?
                                
                                    (2个答案)
                                
                        
                                3年前关闭。
            
                    
当某个元素从显示:无显示到显示状态时,动画总是播放。
如果我想样式自定义复选框。当用户选中或取消选中它时,我只需要播放动画即可。

input[type=checkbox] { opacity: 0; } // native checkbox hidden
input[type=checkbox] ~ .mycheck {
    animation: uncheck 300ms ease-out forwards; // play uncheck animate
}
input[type=checkbox]:checked ~ .mycheck {
    animation: check 300ms ease-out forwards; // play checked animate
}


问题是check,并且uncheck不仅在用户单击时播放。页面加载时也会播放。或当父元素开关隐藏到显示时。例如在引导标签中。

我知道javascript可以轻松处理它。但实际上,此问题来自感兴趣的github项目https://github.com/FezVrasta/bootstrap-material-design/issues/48。那帅哥要通过bootstrap3来实现google资料设计。

目前,我可以想到一种方法(不完美)。 :not(:hover)设置为animation-duration: 1ms;时。让动画迅速结束。但是用户仍然看起来很短。

input[type=checkbox]:not(:hover) ~ .mycheck {
    animation-duration: 1ms;
}


无法设置为0ms。否则,只有在用户将其悬停后才能播放动画。

有没有更好的方法?

最佳答案

您可以使用:not(:hover)考虑的解决方案,并通过以下方式取消动画:

input[type=checkbox]:not(:hover) ~ .mycheck {
    animation: none;
}


或者,我认为这是最好的解决方案,不要使用动画,而应使用转场。这将导致类似的情况(假设您正在对不透明度进行动画处理):

input[type=checkbox] ~ .mycheck {
    opacity: 0;
    transition: opacity .3s ease-out;
}

input[type=checkbox]:checked ~ .mycheck {
    opacity: 1;
}


另外,根据您要实现的浏览器支持而定,请注意供应商前缀,因为Chrome仅在最近才将其放在transition属性中

编辑:经过一些测试,我开始认为仅使用:focus伪类就足够了:

input[type=checkbox]:focus ~ .mycheck {
    animation: uncheck 300ms ease-out forwards;
}
input[type=checkbox]:focus:checked ~ .mycheck {
    animation: check 300ms ease-out forwards;
}


我唯一看到的缺点是,当复选框失去焦点时,动画可能会被取消

关于twitter-bootstrap - 这是跳过所示的css3动画的方法吗? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26127844/

10-10 00:23
查看更多