WEB01_Day04(下)-JS控制页面元素内容、JS组成、常用时间(鼠标、键盘、状态改变)
一、JS控制页面元素内容
1.1 练习
-
计算平方数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>求平方案例</title>
</head>
<body>
<!-- 添加页面元素标签 -->
<input type="text" id="txt">
<input type="button" value="求平方" onclick="fn1()">
<input type="button" value="双倍" onclick="fn2()">
<div id="div1">显示计算结果</div>
<!-- 为页面添加JS代码逻辑 -->
<script type="text/javascript">
/* 定义fn1方法,用于计算数值的平方 */
function fn1() {
/* 使用谷歌提供的简化方案,通过元素id调用属性 */
div1.innerText = txt.value * txt.value;
}
/* 定义fn2方法,用于计算数值的二倍 */
function fn2() {
// div1.innerText = txt.value * 2;
/*
如下方案在进行对于一个数值求和的时候,
因为使用的是+运算符,会出现拼接的现象。
解决方案:利用乘法*1,然后再做一个加法运算
还可以对于当前的数值进行解析处理,然后再进行加法运算
*/
// div1.innerText = txt.value*1 + txt.value*1;
div1.innerText = parseInt(txt.value) + parseInt(txt.value);
}
</script>
</body>
</html>
-
计算器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算器案例</title>
</head>
<body>
<!-- 页面元素标签 -->
<input type="text" id="txt1">
<input type="text" id="txt2">
<input type="button" value="加法" onclick="fn5(1)">
<input type="button" value="减法" onclick="fn5(2)">
<input type="button" value="乘法" onclick="fn5(3)">
<input type="button" value="除法" onclick="fn5(4)">
<div id="div1">显示计算结果</div>
<!-- 添加js脚本代码 -->
<script type="text/javascript">
/* 代码简化方案 */
function fn5(x) {
if(isNaN(txt1.value) || isNaN(txt2.value)){
div1.innerText = "输入的不是一个数字";
//结束方法
return;
}
switch (x) {
case 1:
//加法
div1.innerText = txt1.value*1 + txt2.value*1;
break;
case 2:
//减法
div1.innerText = txt1.value - txt2.value;
break;
case 3:
//乘法
div1.innerText = txt1.value * txt2.value;
break;
case 4:
//除法
div1.innerText = txt1.value / txt2.value;
break;
}
}
/*
在当前案例中,需要在输入框中输入阿拉伯数字进行计算,
如果用户在输入框中,输入的内容不是一个阿拉伯数字,
应该在div的文本中,给用户一个提示"输入的不是一个数字"。
使用isNaN()方法进行判断当前用户在输入框中输入的内容是否是一个数字
如果输入的内容是数字时返回值为false
如果输入的内容不是数字时返回值为true
*/
/* 加法 */