JS监听键盘两个组合键触发的事件

html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>练习移动title>
    <script>
        window.onload=function(){
            var div = document.getElementsByTagName("div")[0];
            //设置两个变量保存键值
            var key1 = 0;
            var key2 = 0;
            //键弹起时设置
            document.onkeyup = function(){
                 key1 = 0;
                 key2 = 0;
            }
            //键按下时
            document.onkeydown=function(e){
                var e = window.event||e;
                var x = parseInt(div.style.left);
                var y = parseInt(div.style.top);
                //判断是否为组合键
                if(key1 == 0){
                    key1 = e.keyCode;
                }else{
                    key2 = e.keyCode;
                }
                //单个键
                if(e.keyCode==37){//
                  // alert("11左");
                    x-=5;
                }else if(e.keyCode==38){//
                  // alert("22上");
                    y-=5;
                }else if(e.keyCode==39){//
                 //  alert("33右");
                    x+=5;
                }else if(e.keyCode==40){//
                  //alert("44下");
                   y+=5;
                }
                //组合键
                if((key1==37 &&key2==38)||(key1==38 &&key2==37)){//左上
                //alert("左上");
                        x-=5;
                        y-=5;
                }else if((key1==39 &&key2==38)||(key1==38 &&key2==39)){//右上
                //alert("右上");
                        x+=5;
                        y-=5;
                }else if((key1==40 &&key2==37)||(key1==37 &&key2==40)){//左下
               // alert("左下");
                        x-=5;
                        y+=5;
                }else if((key1==39 &&key2==40)||(key1==40 &&key2==39)){//右下
                //alert("右下");
                        x+=5;
                        y+=5;
                }
                //赋值
                div.style.left=x+"px";
                div.style.top=y+"px";
            }
        }
    script>
head>
<body>
<div style="width:100px;height:100px;position: absolute; left:700px;top:100px;background-color: red;">div>
body>
html>

你可能感兴趣的:(JS监听键盘两个组合键触发的事件)