微信小程序制作计算器代码(微信小程序计算器怎么制作)

微信小程序制作计算器代码

微信小程序是一种轻量级应用程序平台,生动、形象且使用方便,非常适合不想下载大容量应用的用户。微信小程序也非常适合那些商户和企业需要快速开发小程序的场景,比如制作小型工具类应用,如计算器。本文将介绍微信小程序中如何制作一个简单的计算器。

计算器功能分析

在制作计算器之前,我们首先要考虑该计算器需要实现哪些功能。简单的计算器至少需要实现加、减、乘、除、取相反数、取反百分数、Sqrt等功能。在设计小程序页面布局时,我们可以考虑中间区域为结果展示区域,其余是按键区域。

小程序实现代码

使用WxXml+WXSS+JavsScript实现小程序。使用WxXml负责页面布局,WXSS负责页面样式设计,JavaScript负责计算器逻辑操作。具体的代码如下:

```html

{{result}}

-
+
x
÷


0
1
2
3


4
5
6
7


8
9
+/-
%


.row{
display: flex;
justify-content: space-between;
margin-top: 5px;
}
.key {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
height: 50px;
font-size: 24px;
border: 1px solid #ddd;
}

.result{
min-height: 100px;
display: block;
font-size: 36px;
background: #eee;
line-height: 100px;
text-align: right;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-right: 10px;
}

.active {
background: #ddd;
}


Page({
data: {
result: '',
operator: '',
num1: '',
num2: '',
multi: 1,
},
// 常规 运算
calc() {
let result;
const { operator, num1, num2 } = this.data;
switch (operator) {
case '+':
result = +num1 + +num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
return;
}
this.setData({
result,
operator: '',
num1: result,
num2: '',
});
},
// 数字按键触发
onNum(e) {
const { type } = e.currentTarget.dataset;

if (this.data.operator) {
if (this.data.num2.includes('.')) {
const decimalNum = this.data.num2.split('.')[1];
if (decimalNum.length > 1) return;
}
this.setData({
num2: this.data.num2 + '' + type
});
} else {
if (this.data.num1.includes('.') && type === '.') {
return;
}
this.setData({
num1: this.data.num1 + '' + type
});
}
},
// 运算符按键触发
onOperator(e) {
const { type } = e.currentTarget.dataset;
if (type === '%') {
this.setData({
num1: this.data.result,
num2: '',
operator: '',
multi: 0.01,
});
this.calc();
return;
}
if (type === '+/-') {
if (this.data.operator) {
this.setData({
num2: ((-1) * this.data.num2) + ''
});
} else {
this.setData({
num1: ((-1) * this.data.num1) + '',
});
}
return;
}
if (this.data.operator && this.data.num2) {
this.calc();
}
this.setData({
operator: type,
num2: '',
});
},
// 清除操作
clear() {
this.setData({
result: '',
operator: '',
num1: '',
num2: '',
multi: 1,
});
},
// 删除操作,每次删除最后一位
del() {
if (this.data.operator) {
this.setData({
num2: this.data.num2.substr(0, this.data.num2.length - 1)
});
} else {
this.setData({
num1: this.data.num1.substr(0, this.data.num1.length - 1)
});
}
},
});
```

通过阅读以上代码,我们可以发现实现计算器的核心在于JavaScript代码。

以上就是将微信小程序制作计算器的全部内容。

本文来自投稿,不代表亲测学习网立场,如若转载,请注明出处:https://www.qince.net/xcx0c-2.html

郑重声明:

本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。 若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。

我们不承担任何技术及版权问题,且不对任何资源负法律责任。

如遇到资源无法下载,请点击这里失效报错。失效报错提交后记得查看你的留言信息,24小时之内反馈信息。

如有侵犯您的版权,请给我们私信,我们会尽快处理,并诚恳的向你道歉!

(0)
上一篇 2023年5月4日 下午3:36
下一篇 2023年5月4日 下午3:36

猜你喜欢