简体   繁体   English

如何对 keydown 和 click 事件使用相同的函数?

[英]How can I use the same function for keydown and click events?

I'm trying to listen for two event types ( keydown and click ) and execute the same function (toggling the playing and pausing of some audio files) on both of them.我正在尝试侦听两种事件类型( keydownclick )并在它们两个上执行相同的功能(切换某些音频文件的播放和暂停)。

The event listener for keydown works fine but when I try to use the same function for click , nothing happens. keydown的事件侦听器工作正常,但是当我尝试对click使用相同的函数时,没有任何反应。 Console logging audio is null when using click as event type.使用click作为事件类型时,控制台记录audio为空。

Can anyone shed some light on this?任何人都可以对此有所了解吗?

Please note that I'm trying to do this in vanilla JS only (my code is based on the first project of Wes Bos' Javascript 30 course).请注意,我仅尝试在 vanilla JS 中执行此操作(我的代码基于 Wes Bos 的 Javascript 30 课程的第一个项目)。

Here's the code:这是代码:

  function toggleSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`); 
    const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
    if(!audio) return; 
    if (audio.paused) {
     audio.currentTime = 0; 
     audio.play();
     key.classList.add('playing'); 
      } else {
        audio.pause();
        key.classList.remove('playing');
      }
  };
  function removeTransition(e) {
    if(event.propertyName !== 'transform') return; 
    this.classList.remove('playing'); 
  }
  const keys = document.querySelectorAll('.key');
  keys.forEach(key => key.addEventListener('ended', removeTransition));

  window.addEventListener('keydown',  toggleSound);
  window.addEventListener('click', toggleSound);

you are actually adding this listener in a wrong way, when you use the following code:当您使用以下代码时,您实际上是以错误的方式添加了此侦听器:

window.addEventListener('click', clickSound) window.addEventListener('click', clickSound)

You are running the clickSound method, and inside this method you are adding another listeners for each item in the keys array (which i don't know what is it, but i assume that it's an html element, since you are using addEventListener on it too)您正在运行 clickSound 方法,在此方法中,您正在为 keys 数组中的每个项目添加另一个侦听器(我不知道它是什么,但我假设它是一个 html 元素,因为您在它上面使用了 addEventListener也)

to solve it you can remove this window.addEventListener('click', clickSound) and add the listeners for the keys itself要解决它,您可以删除此 window.addEventListener('click', clickSound) 并为键本身添加侦听器

something like就像是



keys.forEach(key => {
  key.addEventListener('click', e => {
    const dataKey = e.target.dataset.key;
    const audio = document.querySelector(`audio[data-key="${dataKey}"]`);

    if (!audio) return; // Just to be sure the element was found
    if (audio.paused) {
      audio.currentTime = 0;
      audio.play();
      key.classList.add('playing');
    } else {
      audio.pause();
      key.classList.remove('playing');
    }
  });
});

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

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