简体   繁体   English

如何从JavaScript播放CSS过渡效果

[英]How to play css transition effect from javascript

I'm trying to play a sound when user clicks a button on screen. 当用户单击屏幕上的按钮时,我正在尝试播放声音。 I have bound these buttons with keyboard keys. 我已将这些按钮与键盘键绑定在一起。 Like there is a button with id='A' which is bound to the keyboard key 'A'. 就像有一个id ='A'的按钮绑定到键盘键'A'一样。 So if user presses the key'A' from keyboard or presses the on screen button, the java script function written on that button will be called. 因此,如果用户按下键盘上的“ A”键或按下屏幕上的按钮,则会调用写在该按钮上的Java脚本函数。

Here is the problem: 这是问题所在:

I have applied below css on buttons, which works fine if i click the on screen button. 我在按钮上的css下应用了此功能,如果我单击屏幕上的按钮,则效果很好。 The desired ripple effect is shown. 显示了所需的波纹效果。 But when i press the keyboard button, the effect does not work. 但是当我按下键盘按钮时,效果不起作用。

To bind the keys i have written following JS code. 为了绑定键,我编写了以下JS代码。

  document.onkeydown = function(e) { e = e || window.event; var key = (e.which || e.keyCode), pressed = { 65: 'A', 83: 'S' }; if (typeof pressed[key] === 'undefined') return; document.getElementById(pressed[key]).click(); } 
 .button { position: relative; background-color: #4CAF50; border: none; font-size: 28px; color: #FFFFFF; padding: 10px; width: 100px; text-align: center; -webkit-transition-duration: 0.4s; /* Safari */ transition-duration: 0.4s; text-decoration: none; overflow: hidden; cursor: pointer; } .button:after { content: ""; background: #f1f1f1; display: block; position: absolute; padding-top: 300%; padding-left: 350%; margin-left: -20px !important; margin-top: -120%; opacity: 0; transition: all 0.8s } .button:active:after { padding: 0; margin: 0; opacity: 1; transition: 0s } 
 <button class="button" type="button" id="A">A</button> <button class="button" type="button" id="S">S</button> 

So how can i show the ripple effect even when the user presses the keyboard key? 那么,即使用户按下键盘键,我也如何显示涟漪效应?

It seems you cannot use :active alone here since Javascript is unable to trigger that state. 似乎您不能在这里单独使用:active ,因为Javascript无法触发该状态。 Instead additonally create a class .active and put it on the element. 而是另外创建一个.active类,并将其放在元素上。

.button.active:after { ... }

See Triggering CSS :active selector for non-anchor elements 请参阅触发CSS:active选择器以获取非锚元素

Since it kind of touches the topic, the global accesskey attribute might be interesting for you as well. 由于它触及主题,因此全局访问accesskey属性也可能对您很有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM