Execute JS code after pressing the spacebar

匆匆过客 提交于 2019-11-27 07:35:30

问题


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?


回答1:


document.body.onkeyup = function(e){
    if(e.keyCode == 32){
        //your code
    }
}

This will be executed after you hit spacebar.

JSFiddle.




回答2:


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

    }
});



回答3:


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:


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


来源:https://stackoverflow.com/questions/24386354/execute-js-code-after-pressing-the-spacebar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!