红绿灯简单模拟

时间:2023-02-10 15:24:10

红绿灯简单模拟

子文件

 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>子窗口</title>
<style>
//计时文本框的样式
#con{width:50px;height:30px;text-align: center;line-height: 30px;font-size: 20px;}
</style>
</head>
<input type="button" value="开始" onclick="colorTurn()"/>
<input type="text" id="con" />
<body>
<script>
opener.creatDiv() // 在父窗口调用函数
//获取
var inpObj=document.getElementsByTagName("input")[0];
var time=document.getElementsByTagName("input")[1];
var divObj=opener.document.getElementsByTagName("div");
function colorTurn(){
var i=0; // 计数
var jsq="";// 声明一个计时器标记
function red(){
i++;
divObj[0].style.background="red"
divObj[1].style.background="black"
jsq=setTimeout(red,100);
if(i>60){
clearTimeout(jsq)
green();
}
time.value=i;
}
red();
function green(){
i--;
divObj[1].style.background="green"
divObj[0].style.background="black"
jsq=setTimeout(green,100)
if(i<0){
clearTimeout(jsq)
red();
}
time.value=i;
}
}
</script>
</body>
</html>

父文件

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>父窗口</title>
</head>
<body>
<script>
// 打开子窗口
window.open("son.html","","width=400,height=300",false);
function creatDiv(){
for(var i=0;i<2;i++){
// 创建div (红绿灯)
var divObj=document.createElement("div");
// 设置div样式
divObj.style.width="80px";
divObj.style.height="80px";
divObj.style.borderRadius="40px";
divObj.style.float="left";
divObj.style.margin="20px";
divObj.style.border="2px solid #000";
//将新建div添加到body里
document.body.appendChild(divObj)
}
}
</script>
</body>
</html>