Execute JS code after pressing the spacebar

2020-02-06 18:41发布

this is my code in JavaScript:

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

document.getElementById ("balklongwaarde").addEventListener("click", function(){ changeIdValue("balklongwaarde", "60px")});

document.getElementById ("balklevensverwachting").addEventListener("click", function(){ changeIdValue("balklevensverwachting", "60px")});

document.getElementById ("balkhart").addEventListener("click", function(){ changeIdValue("balkhart", "60px")});

document.getElementById ("balklever").addEventListener("click", function(){ changeIdValue("balklever", "60px")});

document.getElementById("balkhersenen").addEventListener("click", function(){ changeIdValue("balkhersenen", "60px")});

I want to execute this code after press on keyup....

Has anyone an idea how?

4条回答
趁早两清
2楼-- · 2020-02-06 18:46

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

    }
});
查看更多
Evening l夕情丶
3楼-- · 2020-02-06 18:46

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);
}
查看更多
萌系小妹纸
4楼-- · 2020-02-06 18:56

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')
  }
})

查看更多
劫难
5楼-- · 2020-02-06 19:04
document.body.onkeyup = function(e){
    if(e.keyCode == 32){
        //your code
    }
}

This will be executed after you hit spacebar.

JSFiddle.

查看更多
登录 后发表回答