代码案例
1 代码案例:猜数字
预期效果
【步骤分解】
- 首先要先能够生成一个随机的数字
- 需要在页面上有一个输入框
- 需要有一个提交按钮,猜完了就点击这个按钮看看猜的对不对
- 最后需要有区域来显示结果
注意事项:
JS的
Math.random()
生成的随机数,是一个[0,1)之间的小数但是咱们要生成的是[1,100]的数
怎么做呢?
我们设得到的的随机数是 N
0<= N <1
N*100 ——> 0<= N <100
N*100+1 ——> 1<= N <101 ( < 101 的意思是可以取 100.5 这样的数值 )
向下取整,也就得到了 [1,100]这样的范围
代码:
<body>
<input type="text">
<button>确定</button>
<div class='screen'></div>
<script>
let input = document.querySelector('input');
let screen = document.querySelector('.screen');
//1.生成一个随机的整数
let toGuess = Math.floor(100 * Math.random() + 1);
console.log(toGuess);
//2.针对按钮的点击操作 进行处理
let button = document.querySelector('button');
button.onclick = function() {
//3.拿到输入框中的数值,然后和toGuess 进行判定
//针对输入框,使用value属性来获取到输入框中的内容
let curNum = parseInt(input.value);//此时拿到的数值是一个字符串类型,转成整数
if(isNaN(curNum)){
screen.innerHTML = '输入非法,请输入数字';
return;
}
if(curNum < toGuess){
//猜低了
screen.innerHTML = '猜低了';
}else if(curNum > toGuess){
//猜高了
screen.innerHTML = '猜高了';
}else{
//猜对了
screen.innerHTML = '猜对了';
}
}
</script>
</body>
2 代码案例:表白墙/留言板
效果展示
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>表白墙</title>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.container {
width: 800px;
margin: 10px auto;
}
.container h2 {
text-align: center;
margin: 30px 0px;
}
.row {
height: 50px;
display: flex;
justify-content: center;
margin-top: 5px;
}
.row span {
height: 50px;
width: 100px;
line-height: 50px;
}
.row input {
height: 50px;
width: 300px;
line-height: 50px;
}
.row button {
width:400px;
height: 50px;
color: white;
background-color:orange;
border: none;
border-radius: 10px;
}
.row button:active {
background-color:grey;
}
</style>
</head>
<body>
<!--这是一个顶层容器,用来放其他元素-->
<div class="container">
<h2>表白墙</h2>
<div class="row">
<span>谁</span>
<input type="text" id="from">
</div>
<div class="row">
<span>对谁</span>
<input type="text" id = "to">
</div>
<div class="row">
<span>说什么</span>
<input type="text" id = "message">
</div>
<div class="row">
<button>提交</button>
</div>
</div>
<script>
let container = document.querySelector('.container');
let fromInput = document.querySelector('#from');
let toInput = document.querySelector('#to');
let messageInput = document.querySelector('#message');
let button = document.querySelector('button');
button.onclick = function() {
//1.把用户输入的内容先获取到
let from = fromInput.value;
let to = toInput.value;
let message = messageInput.value;
if(from =='' || to == '' || message ==''){
return;
}
//2.构造一个div,把这个div插入到 container 的末尾
let newDiv = document.createElement('div');
newDiv.className = 'row';
newDiv.innerHTML = from + "对" + to + "说:" + message;
//3.把div 挂在container里面
container.appendChild(newDiv);
//4.把之前的输入框内容清空
fromInput.value = '';
toInput.value = '';
messageInput.value = '';
}
</script>
</body>
</html>