码迷,mamicode.com
首页 > 移动开发 > 详细

js--去除默认事件连续移动的div

时间:2016-05-27 08:16:56      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1{ width:100px; height:100px; position:absolute; background:#F00; top:0; left:0;}
</style>
<script>
window.onload=function(){
    var oDiv=document.getElementById(‘div1‘);
    var i=r=t=b=false;
document.addEventListener(‘keydown‘,function(ev){
    var oEvent=ev||event;
    
    switch(oEvent.keyCode){
        case 37: i=true; break;
        case 38: r=true; break;
        case 39: t=true; break;
        case 40: b=true; break;
        
        }
        },false);
document.addEventListener(‘keyup‘,function(ev){
       var oEvent=ev||event;
      
      switch(oEvent.keyCode){
          case 37: i=false; break;
          case 38: r=false; break;
          case 39: t=false; break;
          case 40: b=false; break;
         
          }
    
    },false);
    
    setInterval(function(){
        if(i) oDiv.style.left=oDiv.offsetLeft-10+‘px‘;
        if(t) oDiv.style.left = oDiv.offsetLeft + 10 + "px";
        if(r) oDiv.style.top = oDiv.offsetTop - 10 + "px";
        if(b) oDiv.style.top = oDiv.offsetTop + 10 + "px";
        },1)
    
    
    };
</script>
</head>

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

 

js--去除默认事件连续移动的div

标签:

原文地址:http://www.cnblogs.com/hack-ing/p/5533329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!