【问题标题】:keydown trigger css background color changekeydown 触发 css 背景颜色变化
【发布时间】:2019-01-05 04:35:52
【问题描述】:

通过keydown event 触发background-color 更改的最简单方法是什么?目前我有它,当你按下一个键时它会发出声音,但我想让它在每次按下键时改变背景颜色。

这是我的 JS:-

function play(id){
    var audio = document.getElementById(id);    
    audio.play();    
}

function removeTransition(e) {
    if (e.propertyName !== 'transform') return;
    e.target.classList.remove('playing');
}
function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
    if (!audio) return;
    key.classList.add('playing');
    audio.currentTime = 0;
    audio.play();
 }
 const keys = Array.from(document.querySelectorAll('.key'));
 keys.forEach(key => key.addEventListener('transitionend', removeTransition));
 window.addEventListener('keydown', playSound);

谢谢!

【问题讨论】:

    标签: css events background-color keydown


    【解决方案1】:

    HTML:

    <div id="box"></div>
    

    CSS:

    #box {
      height: 200px;
      width: 200px;
      background-color:red;
    }
    

    JS:

    document.addEventListener("keydown", changeBg);
    function changeBg() {
        document.getElementById("box").style.backgroundColor = "green";
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 1970-01-01
      • 2017-04-14
      • 2021-10-02
      • 2014-09-14
      • 2021-02-13
      • 2017-12-10
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多