事件:方向鍵的應用

鍵盤控制Div移動
方向鍵控制方向

定時器控制移動和速度

<div id="div1">
#div1{width:100px;height:100px;background: red;position: absolute;left:40%;top:30%;}
       onload = function () {
            var oDiv = document.getElementById('div1');
            oDiv.timer = null;
            var direct = 0;

            document.onkeydown = function(ev) {
                ev = ev || event;
                direct = ev.keyCode;
                if(oDiv.timer == null){
                    oDiv.timer = setInterval(doMove,50);
                }
            };
            document.onkeyup = function () {
                clearInterval(oDiv.timer);
                oDiv.timer = null;
            };

            function doMove() {
                switch (direct) {
                    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;
                    default:
                        return;
                }
            }
        };



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章