Execute JS code after pressing the spacebar

后端 未结 5 777
心在旅途
心在旅途 2020-12-11 00:21

this is my code in JavaScript:

var changeIdValue =  function(id, value) {
document.getElementById(id).style.height = value;
};

document.getElementById (\"ba         


        
相关标签:
5条回答
  • 2020-12-11 00:38

    keyCode is deprecated. You could use key (the character generated by pressing the key) or code (physical key on the keyboard) instead. Using one or another can have different outputs depending on the keyboard layout.

    document.addEventListener('keydown', (e) => {
        if (e.key === "Space") {
            // Do your thing
        }
    });
    
    0 讨论(0)
  • 2020-12-11 00:45

    In JQuery events are normalised under which event property.

    You can find any key value here eg:spacebar value(32).

    This function may help you.

    $(window).keypress(function(e) {
        if (e.which === 32) {
    
            //Your code goes here
    
        }
    });
    
    0 讨论(0)
  • 2020-12-11 00:46
    document.body.onkeyup = function(e){
        if(e.keyCode == 32){
            //your code
        }
    }
    

    This will be executed after you hit spacebar.

    JSFiddle.

    0 讨论(0)
  • 2020-12-11 00:48

    document.activeElement is whatever element has focus. You'll often find both spacebar and enter firing click on the focused element.

    document.body.onkeyup = function(e){
        if(e.keyCode == 32 || e.keyCode == 13){
            //spacebar or enter clicks focused element
            try {
                doc.activeElement.click();
            }
            catch (e) {
                console.log(e);
            }            
        }
    };  
    

    Then the CSS might be:

    .focusable-thing:hover {
        cursor: pointer;
    }
    .focusable-thing:focus {
        -webkit-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
        -moz-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
        box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
    }
    
    0 讨论(0)
  • 2020-12-11 00:54

    The 2019 version of this would be: (works in all major browsers - Chrome, Firefox, Safari)

    Spec link - https://www.w3.org/TR/uievents/#dom-keyboardevent-code

    code holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value. The un-initialized value of this attribute MUST be "" (the empty string).

    // event = keyup or keydown
    document.addEventListener('keyup', event => {
      if (event.code === 'Space') {
        console.log('Space pressed')
      }
    })

    0 讨论(0)
提交回复
热议问题