JavaScript实现随机显示小星星

来源:互联网 发布:彩虹6号 淘宝 编辑:程序博客网 时间:2024/06/05 09:37
<!DOCTYPE html><html>    <!--实例:随机显示小星星    (1)网页加载完成,利用定时器加载星星    (2)创建图片节点,追加到<body>父节点    (3)设置小星星图片的属性:图片随机大小    (4)图片随机定位坐标(x,y) 图片的显示坐标不要超出浏览器窗口范围    (5)为星星添加onclick事件 单击星星移除图片-->    <head>        <meta charset="UTF-8">        <title>随机显示小星星</title>        <script type="text/javascript">            //页面加载完成开始加载小星星            window.onload = function(){                //设置定时器   1秒钟显示一个小星星                window.setInterval("ShowStart()",1000);            }            //动画主函数            function ShowStart(){                //创建图片节点                var img = document.createElement("img");                //将图片节点追加到body节点下                document.body.appendChild(img);                //设置img的属性                img.setAttribute("src","img/xingxing.PNG");                var width = getRandom(30,80);                img.setAttribute("width",width);                //设置星星的随机坐标                var x = getRandom(0,window.innerWidth-50);                var y = getRandom(0,window.innerHeight-50);                img.setAttribute("style","position: absolute;left:"+x+"px; top:"+y+"px;");                //为星星添加onclick事件属性                img.setAttribute("onclick","removeImg(this)");            }            //随机数函数            function getRandom(min,max){                var random = Math.random()*(max-min) + min;                random = Math.floor(random);                return random;            }            //删除星星函数            function removeImg(obj){                document.body.removeChild(obj);            }        </script>    </head>    <body>    </body></html>
原创粉丝点击