微信小程序计算器代码
时间: 2024-01-13 19:02:55 浏览: 142
以下是微信小程序简易计算器的代码,包括wxml、js和json文件:
wxml文件:
```
<view class="container">
<view class="result">{{result}}</view>
<view class="row">
<view class="btn" bindtap="inputNumber" data-num="7">7</view>
<view class="btn" bindtap="inputNumber" data-num="8">8</view>
<view class="btn" bindtap="inputNumber" data-num="9">9</view>
<view class="btn" bindtap="operator" data-op="+">+</view>
</view>
<view class="row">
<view class="btn" bindtap="inputNumber" data-num="4">4</view>
<view class="btn" bindtap="inputNumber" data-num="5">5</view>
<view class="btn" bindtap="inputNumber" data-num="6">6</view>
<view class="btn" bindtap="operator" data-op="-">-</view>
</view>
<view class="row">
<view class="btn" bindtap="inputNumber" data-num="1">1</view>
<view class="btn" bindtap="inputNumber" data-num="2">2</view>
<view class="btn" bindtap="inputNumber" data-num="3">3</view>
<view class="btn" bindtap="operator" data-op="*">*</view>
</view>
<view class="row">
<view class="btn" bindtap="inputNumber" data-num="0">0</view>
<view class="btn" bindtap="clear">C</view>
<view class="btn" bindtap="calculate">=</view>
<view class="btn" bindtap="operator" data-op="/">/</view>
</view>
</view>
```
js文件:
```
Page({
data: {
result: '0',
num1: '',
num2: '',
operator: ''
},
inputNumber: function(e) {
var num = e.currentTarget.dataset.num;
if (this.data.operator === '') {
this.setData({
num1: this.data.num1 + num,
result: this.data.num1 + num
});
} else {
this.setData({
num2: this.data.num2 + num,
result: this.data.num1 + this.data.operator + this.data.num2 + num
}); }
},
operator: function(e) {
var op = e.currentTarget.dataset.op;
if (op === '+' || op === '-' || op === '*' || op === '/') {
this.setData({
operator: op,
result: this.data.result + op
});
}
},
clear: function() {
this.setData({
result: '0',
num1: '',
num2: '',
operator: ''
});
},
calculate: function() {
var num1 = parseFloat(this.data.num1);
var num2 = parseFloat(this.data.num2);
var operator = this.data.operator;
var result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
break;
}
this.setData({
result: result.toString(),
num1: result.toString(),
num2: '',
operator: ''
});
}
})
```
json文件:
```
{
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "计算器",
"navigationBarTextStyle": "black"
}
```
阅读全文