用js实现点击抽奖
用原生的JS来完成的一个小游戏,进行了简单的点击触发以及判断
css:
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #f7f7f7;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
text-align: center;
width: 300px;
}
h1 {
font-size: 24px;
color: #333;
margin-bottom: 20px;
}
input[type="text"],
input[type="number"] {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 2px solid #ddd;
border-radius: 5px;
font-size: 16px;
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 20px;
font-size: 16px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
margin-top: 10px;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #45a049;
}
.btn {
display: none;
background-color: #008CBA;
}
.btn:hover {
background-color: #007B9F;
}
.alert-message {
font-size: 18px;
color: #333;
margin-top: 20px;
}
.btn-container {
display: none;
}
</style>
html
<div class="container">
<h1>抽奖活动</h1>
<input type="text" id="types" placeholder="请输入年龄">
<button onclick="getOld()" class="buttons">提交</button>
<div class="btn-container">
<input type="number" id="hands" readonly>
<button class="btn" onclick="dclick()">点击</button>
</div>
<div id="message" class="alert-message"></div>
</div>
js:
<script>
const old = document.querySelector('#types');
const buttons = document.querySelector('.buttons');
const clicks = document.querySelector('#hands');
const btn = document.querySelector('.btn');
const message = document.querySelector('#message');
function getOld() {
// 清除之前旧的消息
message.innerHTML = '';
//获取并判断输入框内的值
if (old.value < 18) {
alert('青少年不让抽奖');
} else if (old.value < 25) {
alert('壮年不让抽奖');
} else if (old.value < 60) {
alert('只允许60岁以上老人抽奖');
} else if (old.value > 100) {
alert('请输入正确年龄');
} else {
alert('开始');
//获取并更改点击框为显示状态
document.querySelector('.btn-container').style.display = 'block';
//设置为行内块
clicks.style.display = 'inline-block';
//设置为行内块
btn.style.display = 'inline-block';
//设置一个一次性定时器,当10s后执行内里语句
setTimeout(function () {
if (clicks.value >= 30 && clicks.value < 60) {
message.innerHTML = '手速还不错吧';
} else if (clicks.value >= 60 && clicks.value < 100) {
message.innerHTML = '手速可以啊';
} else if (clicks.value >= 100) {
message.innerHTML = '你用连点器了吧?';
} else if (clicks.value >= 10 && clicks.value < 30) {
message.innerHTML = '菜就多练';
}
//完成以上一切以后清空所有数据,还原为最初样式
getReset();
}, 10000);
}
//若判断错误,即用户输入错误则清空值
old.value = '';
}
function dclick() {
//令第二个输入框内值自增
clicks.value++;
}
//进行清空操作
function getReset() {
old.value = '';
clicks.value = '';
clicks.style.display = 'none';
btn.style.display = 'none';
document.querySelector('.btn-container').style.display = 'none';
}
</script>