javascript每日一练(七)——事件二:键盘事件

时间:2022-06-29 06:57:48

一、键盘事件

  onkeydown触发,  keyCode键盘编码  ctrlKey  altKey  shiftKey

键盘控制div移动

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute;}
</style>
<script>
document.onkeydown = function(ev){
    var oEvent = ev || event;
    var oDiv = document.getElementById('div1');

    switch(oEvent.keyCode){
        case 37:
            oDiv.style.left = oDiv.offsetLeft - 10 +'px';
            break;
        case 38:
            oDiv.style.top = oDiv.offsetTop - 10 +'px';
            break;
        case 39:
            oDiv.style.left = oDiv.offsetLeft + 10 +'px';
            break;
        case 40:
            oDiv.style.top = oDiv.offsetTop + 10 +'px';
            break;
    }
};
</script>
</head>

<body>
<div id="div1"></div>
</body>
</html>

ctrl+enter提交留言

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
window.onload = function(){
    var oTxt1 = document.getElementById('txt1');
    var oTxt2 = document.getElementById('txt2');
    var oBtn = document.getElementById('btn1');    

    oBtn.onclick = function(){
        oTxt1.innerHTML += oTxt2.value+'\n';
        oTxt2.value = '';
    };

    document.onkeydown = function(ev){
        var oEvent = ev || event;
        //alert(oEvent.keyCode);
        if(oEvent.ctrlKey && oEvent.keyCode == 13 ){
            oBtn.click();
        }
    };
};
</script>
</head>

<body>
<textarea id="txt1" rows="10" cols="40"></textarea><br />
<input type="text" id="txt2" /><input type="button" id="btn1" value="提交"/>(ctrl+enter)
</body>
</html>