如何将两个不同的箭头键和两个不同的变量组合在一起

how do I combine code for two different arrow key's with two different vars?

本文关键字:两个 变量 组合 在一起      更新时间:2023-09-26

我有一些代码,箭头键向下触发。但我想要相同的代码,但要用另一个变量,并将箭头键置于箭头键向下的状态。我在这段代码中有2个div,这是一个在css中绘制的栏。当你按住箭头键时,你会看到数值在变化。我想要相同的,但有两个其他的div在箭头键左。如何添加代码,并且两者都能工作。

var changeIdValue = function () {
 var current = document.getElementById('balklongwaarde').clientHeight - 15 + 'px';
'use strict'
document.getElementById('balklongwaarde').style.height = current;
var current = document.getElementById('balklevensverwachting').clientHeight - 7.5 + 'px';
'use strict'
document.getElementById('balklevensverwachting').style.height = current;
};
var intervalID;
 //through arrow down values are changing//
window.onkeydown = function(e){
if(e.keyCode == 40){
    if(typeof intervalID == 'undefined') {
        intervalID = window.setInterval(changeIdValue, 10);       
    }
};

//through arrow down values are changing//
 window.onkeyup = function(e){
if(e.keyCode == 40){
    window.clearInterval(intervalID);
    intervalID= undefined;
 }
};
}

http://jsfiddle.net/MhTU9/在jsfiddle中,我添加了左箭头键的代码,但它不起作用

您需要使用addEventListener绑定多个回调。https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

演示。

Code DRY版本。

function bind(callback, keyCode) {
    var interval;
    window.addEventListener('keydown', function(e){
        if(e.keyCode === keyCode) {
            if(typeof interval === 'undefined') {
                interval = setInterval(callback, 10);
            }
        }
    }, false);
    window.addEventListener('keyup', function(e){
        if(e.keyCode === keyCode) {
            interval = clearInterval(interval);
        }
    }, false)
}
bind(changeIdValue, 37);
bind(changeWaarde, 40);