gpt4 book ai didi

javascript - javascript中keyup和keydown的工作有什么区别?

转载 作者:行者123 更新时间:2023-11-29 20:35:13 25 4
gpt4 key购买 nike

我一直在学习 javascript 中的按键事件,想知道为什么我在 keyupkeydown 中得到不同的结果。例如。如果我分配一个带有 id 的输入并通过它传递一个 addEventListner[reffer code] 那么如果我在 keydown 事件中键入“1234”我得到的输出为“123”并且这个问题不会发生在 keyup 事件中.

简而言之,我只是想问问为什么万一keydown 字符(在输入中键入)的编号不等于否。输出中显示的字符。 keyup 不会发生这种情况,我应该使用哪一个?

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="in" placeholder="enter a value" style="border: solid; margin: 15px; padding: 5px">
<div style="border: 5px solid black; margin:10px; width:30vw; height: 15vh">
Keydown result: <div id="keydown"></div>
</div>
<div style="border: 5px solid black; margin:10px; width:30vw; height: 15vh">
Keyup result:<div id="keyup"></div>
</div>
</body>
</html>

<script>
document.getElementById('in').addEventListener('keydown', runevent);

function runevent(e){

document.getElementById('keydown').innerText = e.target.value;

}

document.getElementById('in').addEventListener('keyup', runevent1);

function runevent1(e){

document.getElementById('keyup').innerText = e.target.value;

}


</script>

最佳答案

in short i just wanted to ask that why in case of keydown no of character(typed in input) is not equal to no. of character displayed in output. this doesnt happens with keyup and which one should i use?

如果您对字符感兴趣,如果您想处理事件生成的字符,请使用keypress,或者如果您希望使用input您只需要最新的字段值。

  • keydown在将字符添加到字段之前触发,这就是为什么在键入 1234 后看不到 4 的原因。 (如果您阻止 keydown 的默认操作,则永远不会添加该字符。)

  • beforeinput在输入发生变化之前触发(例如,如果变化的原因是按键,则在字符被添加之前)。

  • keypress在添加 Angular 色之前也会被触发。
    注意 keypress 已弃用,请参阅beforeinputkeydown .

  • input添加 Angular 色后触发。

  • keyup添加 Angular 色后触发。

这可能有助于您查看顺序:

const input = document.getElementById("field");
const output = document.getElementById("output");

function handleEvent(e) {
output.insertAdjacentHTML("beforeend",
"<pre>" + e.type + ": " + input.value + "</pre>"
);
}

input.addEventListener("keydown", handleEvent);
input.addEventListener("keyup", handleEvent);
input.addEventListener("keypress", handleEvent);
input.addEventListener("input", handleEvent);
#output pre {
margin-top: 0;
margin-bottom: 0;
}
<input type="text" id="field">
<div id="output"></div>

关于javascript - javascript中keyup和keydown的工作有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56906229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com