—— 此篇开始 ——
目的:主要考查的就是使用jQuery对DOM元素的操作,以及一个eval()方法的使用
功能:普通的加减乘除运算功能、删除功能、清空功能、历史查看功能
代码:
HTML部分:
<div id="box">
<!-- 标题 -->
<h1>计算器</h1>
<!-- 屏幕 -->
<input type="text" id="screen" readonly value="" />
<!-- 按钮 -->
<div id="btn">
<button>1</button>
<button>2</button>
<button>清空</button>
<button>3</button>
<button>4</button>
<button>+</button>
<button>5</button>
<button>6</button>
<button>-</button>
<button>7</button>
<button>8</button>
<button>*</button>
<button>9</button>
<button>0</button>
<button>/</button>
<button>删除</button>
<button>历史</button>
<button>=</button>
</div>
</div>
JS部分:
$(document).ready(function () {
//遍历每一个按钮
$("#btn").each(function () {
//创建一个数组存历史记录
const result = [];
// 给每一个按钮添加点击事件
$("button").click(function () {
// 让屏幕显示内容,且后续内容拼接显示,如果一开始点击运算符则不显示在屏幕上
let content = $("#screen").val() + this.innerText;
if (
content.charAt(0) == "+" ||
content.charAt(0) == "-" ||
content.charAt(0) == "*" ||
content.charAt(0) == "/"
) {
$("#screen").val("");
} else {
$("#screen").val(content);
}
//清空功能
if ($(this).html() == "清空") {
$("#screen").val("");
//计算功能
} else if ($(this).html() == "=") {
$("#screen").val(
eval(
$("#screen")
.val()
.substring(0, $("#screen").val().length - 1)
)
);
result.push($("#screen").val());
//删除功能
} else if ($(this).html() == "删除") {
$("#screen").val(
$("#screen")
.val()
.substring(0, $("#screen").val().length - 3)
);
} else if ($(this).html() == "历史") {
//讲数组里存的历史记录用逗号隔开并显示
$("#screen").val(result.join("、"));
}
});
});
});
</script>
CSS部分:(样式可以自己写)
<style>
/* 公共样式 */
* {
margin: 0;
padding: 0;
}
.clears {
clear: both;
height: 0;
overflow: hidden;
font-size: 0;
line-height: 0;
}
img {
border: none;
}
input,
button,
textarea,
select {
outline: none;
vertical-align: middle;
}
ol,
ul,
li {
list-style: none;
}
a {
text-decoration: none;
}
body {
background-color: antiquewhite;
}
/* 计算器样式 */
#box {
width: 35%;
height: 730px;
background-color: black;
margin: 20px auto auto auto;
/* border: 1px solid black; */
border-radius: 18px;
box-shadow: 0 100px 100px hsl(0deg 0% 0% / 0.075),
0 20px 20px hsl(0deg 0% 0% / 0.075),
0 40px 40px hsl(0deg 0% 0% / 0.075),
0 40px 40px hsl(0deg 0% 0% / 0.075),
0 120px 120px hsl(0deg 0% 0% / 0.075);
}
h1 {
color: white;
font-weight: 400;
text-align: start;
padding-left: 25px;
}
#screen {
margin-top: 10px;
width: 92%;
border: none;
margin: auto;
height: 20%;
background-color: azure;
border-radius: 18px;
font-size: 70px;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
text-align: right;
}
#btn {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
width: 92%;
margin: auto;
margin-top: 10px;
}
button {
width: 30%;
height: 80px;
margin-top: 5px;
border-radius: 18px;
background-color: #caccd1;
border: none;
font-size: 25px;
cursor: pointer;
}
button:hover {
background-color: azure;
}
</style>
效果:
计算器演示