微信小程序 通过输入圆的半径而输出面积 带注释
时间: 2023-08-21 11:03:34 浏览: 65
以下是一个简单的微信小程序,可以通过输入圆的半径,计算出对应圆的面积,并在页面上显示结果:
```html
<!--index.wxml-->
<view class="container">
<view class="title">圆面积计算器</view>
<view class="input-container">
<view class="label">请输入圆的半径:</view>
<input class="input" type="number" placeholder="请输入圆的半径" bindinput="onInputRadius"/>
</view>
<view class="result-container" wx:if="{{area}}">
<view class="label">圆的面积为:</view>
<view class="result">{{area.toFixed(2)}} 平方厘米</view>
</view>
</view>
```
```css
/*index.wxss*/
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.title {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
.input-container {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.label {
font-size: 18px;
}
.input {
width: 100px;
height: 30px;
border: 1px solid #ccc;
margin-left: 10px;
text-align: center;
}
.result-container {
display: flex;
align-items: center;
margin-top: 20px;
}
.result {
font-size: 18px;
font-weight: bold;
}
```
```javascript
//index.js
Page({
data: {
area: null, // 圆的面积
radius: null, // 圆的半径
},
// 输入圆的半径时触发
onInputRadius: function (e) {
const radius = e.detail.value // 获取输入的半径
const area = Math.PI * radius * radius // 计算圆的面积
this.setData({ radius, area }) // 更新数据
}
})
```
在这个小程序中,我们使用了一个输入框,让用户输入圆的半径。当用户输入半径后,会触发 `bindinput` 事件,调用 `onInputRadius` 函数。在该函数中,我们使用输入的半径计算圆的面积,并通过 `setData` 函数更新数据。页面上会根据更新后的数据显示对应的结果。
需要注意的是,由于面积可能是一个小数,我们在显示时需要保留两位小数,可以使用 `toFixed` 方法进行格式化。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)