我有一个keydown事件的代码。我的代码就像, 当我按下向下箭头键(40)这个函数verticalSlideUp();开始工作了。 但是当我按下此键(40)两次,然后按键(38),然后键(40)工作两次,完成后,键(38)开始工作。
但我想做的是:当我按任意一个键(40)(38)(13)时,那么 立即停止其他功能。当前功能将启动。
注意:我在stackoverflow
中遵循了这个答案如何在JavaScript中避免自动重复的keydown事件?
这在我的代码中:
var allowed = true;
$(document).keydown(function(e) {
if (e.repeat != undefined) {
allowed = !e.repeat;
}
if (!allowed) return;
allowed = false;
if (controlsEnabled) {
if (e.keyCode == 38) {
allowed = true;
verticalSlideDown();
console.log("pressed key for Down : " + e.keyCode);
}
if (e.keyCode == 40) {
allowed = true;
verticalSlideUp();
console.log("pressed key for Up: " + e.keyCode);
}
if (e.keyCode == 13) {
allowed = true;
var div = $(".scroll-inner-container");
console.log("pressed key for stop : " + e.keyCode);
div.stop();
}
}
});
答案 0 :(得分:1)
您可以通过功能方式执行此操作。易于测试和鼓励代码可重用。
例如:
const ENTER = 13;
const RIGHT = 39;
const DOWN = 40;
const once = (fn) => {
let chached = null;
return function (key) {
return chached === key ? void 0 : ((chached = key), fn.apply(this, arguments))
}
}
const logger = (log) => (x) => log(x);
const included = (keys) => (key) => keys.indexOf(key) > -1;
$(document).ready(() => {
const allowedKeys = included([ENTER, RIGHT, DOWN]);
const log = logger(console.log);
const program = once((x) => {
switch (x) {
case ENTER:
log(x)
break;
case RIGHT:
log(x)
break;
case DOWN:
log(x)
break;
default:
log('Unhandled keys')
}
});
$(document).keydown((e) => {
if (allowedKeys(e.keyCode)) program(e.keyCode)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我希望这会有所帮助。
答案 1 :(得分:0)
添加一个记住按下的键的键码的变量,并将其与侦听器功能进行比较:
var allowed = true;
var previousKeyPress = null;
$(document).keydown(function(e) {
if (e.repeat != undefined) {
allowed = !e.repeat;
}
if (!allowed) return;
allowed = false;
if (controlsEnabled) {
if (e.keyCode == 38 && previousKeyPress != 38) {
allowed = true;
verticalSlideDown();
console.log("pressed key for Down : " + e.keyCode);
}
if (e.keyCode == 40 && previousKeyPress != 40) {
allowed = true;
verticalSlideUp();
console.log("pressed key for Up: " + e.keyCode);
}
if (e.keyCode == 13 && previousKeyPress != 13) {
allowed = true;
var div = $(".scroll-inner-container");
console.log("pressed key for stop : " + e.keyCode);
div.stop();
}
previousKeyPress = e.keyCode;
}
});
答案 2 :(得分:0)
跟踪最后一个键,尝试以下
<Condition Binding="{Binding RelativeSource={RelativeSource AncestorType=telerik:RadGridView}, Path=Columns[0].IsVisible}" Value="True" />