你想体验后宫选妃吗?js带你体验后宫选妃
1.点击开始,启动定时器,获取当前时间置于文本框中,每隔10秒记录下来选中的妃子,点击去重,可以去除重复的妃子名
2.点击停止,停止选妃
效果实现:
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
当前时间:
<input type="text" id="time" value="">
<input type="button" value="开始" id="st" onclick="start2()">
<input type="button" value="停止" id="sp" onclick="stop2()">
<h3 style="color: #ff2340" id="h3">开始选妃啦!</h3>
<button onclick="start3()">开始选美女</button>
<button onclick="stop2()">选中美女</button>
<br>
选中的妃子有:<p id="name" style="border: 1px solid red;width: 500px;height: 20px"></p>
<button onclick="arrange()" id="beautyNames">去重</button>
<br>
<div style="border: 1px solid blue;width: 400px;height: 300px" id="div2"/>
</body>
<script>
let h3 = document.getElementById("h3");
let count=0;
let arr = ["妲己", "西施", "貂蝉","金莲","玉龙"]
function start3() {
s2 = setInterval(function () {
if (count == 5) {
count = 0
}
div2.style.backgroundImage = "url(img/"+arr[count]+".jpg)";
h3.innerText="虎子选中了:"+arr[count]
count++
}, 50)
}
let name = document.getElementById("name");
let Listname = []
let s2;
function start2() {
let stime1
s2 = setInterval(function () {
let time1 = new Date()
time.value = time1.toLocaleString();
if (time1.getSeconds() == 30 || time1.getSeconds()==0 ||
time1.getSeconds()== 10 ||time1.getSeconds()==20||
time1.getSeconds()==40||time1.getSeconds()==50) {
stime1=new Date().getSeconds();
start3()
}else{
let stime2=new Date().getSeconds();
if (stime2-stime1==5){
stop2()
Listname.push(arr[--count])
name.innerText=Listname
}
}
}, 1000)
}
function stop2() {
clearInterval(s2)
}
function arrange() {
let name = document.getElementById("name");
//1,将整个妃子的名字拆开,形成一个数组
bnames=name.innerText.split(",")
console.log(bnames)
//2,定义一个新的数组
let newNames=[]
//3,降低一个数组中的元素诸葛放入新的数组中,判断新数组中是否存在,如果不存在,才放入
for (let i = 0; i < bnames.length-1; i++) {
let flag = false
for (let name of newNames){
if (name == bnames[i]){
flag=true
break
}
}
if (!flag){
newNames.push(bnames[i])
}
}
//4,将新数组放入文本框中
name.innerText = newNames
}
</script>
</html>