简体   繁体   中英

HTML/CSS/JS - Changing style of different <td>s only while ctrl/shift/alt key is held down

I'm currently trying to build a webpage as a way of learning event handlers, though I'm having trouble figuring out what I need to do in order to make this work...

Right now, I have a table with 4 cells in a row. I've got them styled as such.

#testCtrl, #testShift, #testAlt, #testMeta {
  background-color: black;
  color: white
  ...
}

What I'm trying to do is change the background color of the cell when the appropriate key is held down. Problem is - I'm unfamiliar with the syntax and what I can and can't do... All I know at this point is that I need to assign the specific td, via ID, to a variable then modify that variable.

var _ctrlPress = document.getElementById("testCtrl");

I'm just not sure how to test against whether or not the ctrl key is currently being pressed or not though and I'm not finding much information online about it, most likely due to poor knowledge of what to search for.

Also, I'd prefer to not go the jquery route at this time.

I apologize for the ignorance, and thank you much for your time.

Edit: After some advice from the comments, here is what I've come up with. Still errors when applying to a bigger file, though the same concept works fine in a small test HTML doc I've been tinkering with... I'm lost, ha.

Script section:

window.addEventListener("keydown", function(ev) {
    var modP = ev.key;
    if ( modP=== "Shift" ) document.getElementById("testShift").classList.add("highlight");
});

Style section:

#testCtrl, #testShift, #testAlt, #testMeta {
  background: black;
  color: white
}

.highlight {
  background: white !important;
  color: black !important;
}

And finally, the HTML section (or at least the relevant bits):

<tr>
  <td id="fillShift"> Shift
  <td id="fillCtrl"> Ctrl
  <td id="fillAlt"> Alt
  <td id="fillMeta"> Meta
</tr>

Where am I messing up?

Again, I apologize for my ignorance. Thank you so much for your time.

Add 2 eventListener to window. 1 for keydown and 1 for keyup. on keydown, change the color. on keyup, change the color back

 window.addEventListener("keydown",function(e){ if(/^1[6-8]$/.test(e.keyCode)){ document.body.style.backgroundColor="#f00"; } }); window.addEventListener("keyup",function(){ document.body.style.backgroundColor="#aaa"; }); 
 <body style="background-color:#aaa;"></body> 

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