Javascript图像不会停在窗口的边缘

时间:2013-12-01 18:32:40

标签: javascript html image

我正在尝试使用Javascript中的箭头键移动图像,并防止它移出屏幕。代码似乎有助于防止左侧,但不是正确的。这是我的代码。任何的意见都将会有帮助。谢谢!

<html>
    <head>
        <style>
            *{
                margin:0; 
                padding:0;
                overflow:hidden;
            }
            html, body{
                height: 100%;
                width: 100%;
                margin: 0;
            }
        </style>
    </head>
    <body onkeydown="checkKey();">
        <img id="player" src="left.gif" />

        <script type="text/javascript">
            var image = document.getElementById('player');

            image.style.left = '0px'; 
            image.style.position= 'relative'; 

            function checkKey(event){
                event = event || window.event;
                var keycode = event.charCode || event.keyCode;
                if(keycode === 39){
                    moveRight();
                }
                if(keycode === 37){
                    moveLeft();
                }
            }

            if (image.style.left < screen.width + 'px'){
                image.style.left = parseInt(image.style.left,10) + 10 + 'px';
            }

            function moveLeft(){
                if (image.style.left > 0 + 'px'){
                    image.style.left = parseInt(image.style.left, 10) - 10 + 'px';
                }
            }
        </script>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

试试这个|的 DEMO

var image;
window.onload=function(){
image = document.getElementById('player');
image.style.left = '0px'; 
image.style.position= 'relative';  
}

function checkKey(event)
{
  event = event || window.event;
  var keycode = event.charCode || event.keyCode;
  if(keycode === 39)
   {
    moveRight();
   }
  if(keycode === 37)
   {
    moveLeft();
   }
}

function moveLeft()
 {
   if (parseInt(image.style.left) > 0)
   {
    image.style.left = parseInt(image.style.left, 10) - 10 + 'px';
   }
 }
function moveRight()
 {
    var parentWidth = image.parentNode.offsetWidth;
   if (parseInt(image.style.left)+image.offsetWidth <parentWidth)
   {
    image.style.left = parseInt(image.style.left, 10) + 10 + 'px';
   }
 }