题目一:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<script>
window.onload=function(){
let txt=document.getElementById("txt");
let st=document.getElementById("st");
let form=document.forms[0];
form.onsubmit=function(){
if(txt.value==""){
alert("请先写一些内容");
txt.focus();
return false;
}
}
document.onkeydown = function(ev){
if(ev.keyCode==13&&document.activeElement === form) {
form.submit();
}
}
}
</script>
</head>
<body>
<form action="#" id="fm">
<input type="text" id="txt" name="txt">
<input type="submit" id="st" name="st">
</form>
</body>
</html>
相关知识:
event.keyCode可以返回被敲击的按键生成的Unicode字符码。
对于keydown和keyup事件,它指定了被敲击的键的虚拟键盘码。虚拟键盘码可能和使用的键盘的布局相关。详细参阅event.keyCode
document.activeElement此属性可以返回页面中获得焦点的元素(即返回当前页面激活元素的功能)。特别说明:此属性是只读属性。