您的位置:首页 > Web前端 > JavaScript

js学习之动态创建html元素

2009-07-16 08:55 309 查看
最近在学习js 写了个简单的效果,菜鸟可以学习学习,基本原理:使用随即数设置top 和left的值,争取慢慢改进效果

请输入内容

<!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>
body{margin:0;padding:0;}
.sky{background:#000;width:1000;height:500px; position:relative;}
#s{ background:#FFF; width:1px; height:1px; overflow:hidden; position:absolute;}
</style>
</head>

<body>
<div class="sky" id="sky"></div>
<button id="creatstar" onclick="creatstars()">没事造星星玩</button>
<script>
function $(id){ return document.getElementById(id);};

function creatstars(){
var star = document.createElement("div");
star.id = "s";
var posX = Math.floor(Math.random(star.style.top)*400+100);
var posY = Math.floor(Math.random(star.style.left)*1000+1);
$("sky").appendChild(star);
star.style.top = posX + "px";
star.style.left = posY + "px";
}

</script>
</body>
</html>
本文出自 “心灵的旅程” 博客,请务必保留此出处http://thinkingod.blog.51cto.com/255015/178824
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: