简体   繁体   中英

How to remove div class using keyup function?

i want to ask you about keyup event listener, mine is not working. when i press the key, it adds pressed class to the div. but when i release the key it won't remove the class

 function keyPressed(e){ const key = document.querySelector(`.key[data-key="${e.keyCode}"]`); key.classList.add('pressed'); } function removePressed(e) { if(e.propertyName !== 'opacity') return; this.classList.remove('pressed'); } const keys = document.querySelectorAll('.key'); keys.forEach(key => key.addEventListener('keyup', removePressed)) window.addEventListener('keydown', keyPressed);
 .pressed { transform: scale(1.0); opacity: 0.7; }
 <div data-key="55" class="key item6"> <kbd>7</kbd> </div>

Try with

HTML:

<div data-key="55" class="key-item6">
      <kbd>7</kbd>        
    </div>

JS:

$('.key-item6').keyup(function () {
    if ($.trim($('.key-item6').val()).length) {         
        $(this).removeClass('pressed');
    }
});

It's hard to tell, but you can do some simple debugging. Change the following line of code:

  this.classList.remove('pressed');

To this:

  console.log(this.classList)

Here's how it should look:

function keyPressed(e){
  const key = document.querySelector(`.key[data-key="${e.keyCode}"]`);
  key.classList.add('pressed');
}
function removePressed(e) {
  if(e.propertyName !== 'opacity') return;
  console.log(this.classList)
}
const keys = document.querySelectorAll('.key');
keys.forEach(key => key.addEventListener('keyup', removePressed))
window.addEventListener('keydown', keyPressed);

If the console displays your element with the class you want to remove, you're on the right track!

The problem is with the event handler. You are attaching the event handler to key while that is not in focus. So your keyup event actually triggered on window .

If you really want to use keyup on the .key use tabindex and focus to the pressed element first. See the attached code.

 function keyPressed(e){ const key = document.querySelector(`.key[data-key="${e.keyCode}"]`); key.classList.add('pressed'); key.focus(); } function removePressed(e) { // if(e.propertyName !== 'opacity') return; this.classList.remove('pressed'); } const keys = document.querySelectorAll('.key'); keys.forEach(key => key.addEventListener('keyup', removePressed)) window.addEventListener('keydown', keyPressed); 
 .pressed { transform: scale(1.0); opacity: 0.7; } 
 <div data-key="55" class="key item6" tabindex=0> <kbd>7</kbd> </div> 

Also, e.propertyName is undefined causing it to return.

My suggestion is to bind keyup to window and use the same method as keyPressed to remove from classlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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