首页 > 移动平台 > 详细

用js实现图片(小球)在屏幕上上下左右移动

时间:2018-10-16 22:51:40      阅读:326      评论:0      收藏:0      [点我收藏+]
<html>
<head>
    <title>Document</title>

</head>
<body style="background-image:URL(‘./b1.png‘)">
<div id="sundiv" style="position:absolute">
<img src="太阳.png"/>
</div>
<script language="javascript" type="text/javascript">
        
            //定义全局变量
            directX=1;//x轴的方向
            directY=1;//y轴的方向
            //上面两个全局变量似乎没有生效
            sunX=0;//小太阳的坐标x
            sunY=0;//小太阳的坐标y
        function sunMove(){

            sunX+=directX;
            sunY+=directY;
            //这条语句无法执行,竟然是因为<!doctype html>存在

            //修改div的left top
            sundiv.style.top=sunY+"px";
            //window.alert(sunY);
            //window.alert(sundiv.style.top);
            sundiv.style.left=sunX+"px";
            //判断什么时候,转变方法
            //x方法(offsetWidth可以返回当前这个对象的实际宽度)
            if(sunX+sundiv.offsetWidth>=document.body.clientWidth||sunX<=0){
                //window.alert(directX);
                //directX-=directX;
                directX=-directX;
            }
            //判断y
            if(sunY+sundiv.offsetHeight>=document.body.clientHeight||sunY<=0){
                //directY-=directY;
                directY=-directY;
                //window.alert(directY);
            }
        }

        setInterval("sunMove()",3);
        //这里写的是setInterval("sunMove()",100);,而不是
        //setInterval("sunMove",100);
    </script>
</body>
</html>
<!-- 运行上述代码时,出现一个巨坑,浏览器没有更新代码,害我刷新对运行结果根本影响。还有<!DOCTYPE html>这句话使代码无法正确运行 -->

 

用js实现图片(小球)在屏幕上上下左右移动

原文:https://www.cnblogs.com/liaoxiaolao/p/9801115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!