<script>
var toRight=true;
var toDown=true;
function move(){
//浏览器的宽度
var bWidth=document.documentElement.clientWidth;
//浏览器的高度
var bHeight=document.documentElement.clientHeight;
//图片所在层的宽度
var divWidth=document.getElementById("myDiv").offsetWidth;
//图片所在层的高度
var divHeight=document.getElementById("myDiv").offsetHeight;
//图片左边界能到达到右边的最大距离
var maxLeft=bWidth-divWidth;

//图片左边距离到浏览器最左边的距离
var left=document.getElementById("myDiv").style.pixelLeft;
//图片上边距离到浏览器上边的距离
var top=document.getElementById("myDiv").style.pixelTop;
//图片上边界能到达下边的最大距离
var maxTop=bHeight-divHeight;

//判断
if(left<0)
{
toRight=true;
}
if(left>maxLeft)
{
toRight=false;
}

if(top<0)
{
toDown=true;

}
if(top>maxTop)
{
toDown=false;
document.getElementById("myDiv").style.pixelTop-=2;
}

if(toRight)
{
//图片向右走
document.getElementById("myDiv").style.pixelLeft+=2; }else
{
document.getElementById("myDiv").style.pixelLeft-=2;
}

if(toDown)
{
document.getElementById("myDiv").style.pixelTop+=2;
}
else
{
document.getElementById("myDiv").style.pixelTop-=2;
}
//移动的方法
setTimeout("move()",10);
}</script>
</head>
<body >
<input value="move" onclick="move()" type=button>
<div id="myDiv" style="position:absolute">
<img src="exclam.gif" ></div>
</body>
</html>

解决方案 »

  1.   

     不好意思,我是楼主,下面的代码是正确的,上面的别看了
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>
    </title>
    <script>
    var toRight=true;
    var toDown=true;
    function move(){
    //浏览器的宽度
    var bWidth=document.documentElement.clientWidth;
    //浏览器的高度
    var bHeight=document.documentElement.clientHeight;
    //图片所在层的宽度
    var divWidth=document.getElementById("myDiv").offsetWidth;
    //图片所在层的高度
    var divHeight=document.getElementById("myDiv").offsetHeight;
    //图片左边界能到达到右边的最大距离
    var maxLeft=bWidth-divWidth;

    //图片左边距离到浏览器最左边的距离
    var left=document.getElementById("myDiv").style.pixelLeft;
    //图片上边距离到浏览器上边的距离
    var top=document.getElementById("myDiv").style.pixelTop;
    //图片上边界能到达下边的最大距离
    var maxTop=bHeight-divHeight;

    //判断
    if(left<0)
    {
    toRight=true;
    }
    if(left>maxLeft)
    {
    toRight=false;
    }

    if(top<0)
    {
    toDown=true;

    }
    if(top>maxTop)
    {
    toDown=false;

    }

    if(toRight)
    {
    //图片向右走
    document.getElementById("myDiv").style.pixelLeft+=2; }else
    {
    document.getElementById("myDiv").style.pixelLeft-=2;
    }

    if(toDown)
    {
    document.getElementById("myDiv").style.pixelTop+=2;
    }
    else
    {
    document.getElementById("myDiv").style.pixelTop-=2;
    }
    //移动的方法
    setTimeout("move()",10);
    }</script>
    </head>
    <body >
    <input value="move" onclick="move()" type=button>
    <div id="myDiv" style="position:absolute">
    <img src="exclam.gif" ></div>
    </body>
    </html>
      

  2.   

    <input value="move" onclick="move()" type=button> // 不要这个window.onload = move;