此文為js 利用滑動條實作投資電腦,并且對複投與非複投的盈利進行對比。如下圖:
技術方面就用到一個簡單的滑動條,因為感覺比較簡單是以打算手寫一下,不想再因為這一個小東西引入一個龐大的UI插件,該文就此誕生。
産品需求
- 本金每 100 移動一格
- 年利率每 0.5 移動一格
- 計算複投與不複投的年收益
配置參數
data() {
return {
balance: "1000", // 本金
rate: "8", // 利率
maxBalance: "20000", // 最大學金
maxRate: "30", // 最大利率
balancePercent: "", // 本金百分比
ratePercent: "", // 利率百分比
balanceStep: 100, // 本金每次滑動的最小步數
rateStep: 0.5, // 利率每次滑動的最小步數
touchx: 0 //x軸移動距離
};
},
滾動條核心js
// 移動端事件
onTouchEvent(e) {
// 滑塊移動橫向距離
this.touchx = e.touches[0].pageX - 40;
this.computedAmount(e.target.id);
},
// pc 端事件
onMouseEvent(e) {
// 滑塊移動橫向距離
this.touchx = event.offsetX - 12;
this.computedAmount(e.target.id);
document.onmousemove = event => {
if (event.target.className == "pro-mask") {
this.touchx = event.offsetX - 12;
this.computedAmount(e.target.id);
}
};
document.onmouseup = () => {
document.onmousemove = document.onmouseup = null;
};
}
計算滾動條數值
methods: {
// 計算本金
getBalance() {
// 計算滾動條百分比
let p = new BigNumber(this.touchx)
.div(this.$refs.progress.offsetWidth)
.times(this.maxBalance)
.idiv(this.balanceStep) //整除,保留0位小數
.div(this.maxBalance)
.times(this.balanceStep)
.times(100)
.toFixed(2);
this.balancePercent = p - 0 > 100 ? 100 : p;
// 計算本金金額
let num = new BigNumber(this.balancePercent)
.div(100)
.times(this.maxBalance)
.toFixed(0);
this.balance = num - 0 > this.maxBalance ? this.maxBalance : num;
},
// 計算利率
getRate() {
// 計算滾動條百分比
let p = new BigNumber(this.touchx)
.div(this.$refs.progress.offsetWidth)
.times(this.maxRate)
.idiv(this.rateStep) //整除,保留0位小數
.div(this.maxRate)
.times(this.rateStep)
.times(100)
.toFixed(1);
this.ratePercent = p - 0 > 100 ? 100 : p;
// 計算年利率數值
let num = new BigNumber(this.ratePercent)
.div(100)
.times(this.maxRate)
.toFixed(1);
this.rate = num - 0 > this.maxRate ? this.maxRate : num;
},
}
通過移動滾動條計算數值
methods:{
computedAmount(type = "balance") {
this.touchx = this.touchx > 0 ? this.touchx : 0;
if (type == "rate") {
this.getRate();
} else {
this.getBalance();
}
},
}
計算年收益
computed: {
// 複投年收益
compounded() {
let num = this.balance;
for (let i = 0; i < 365; i++) {
num = new BigNumber(num)
.times(this.rate)
.div(36500)
.plus(num)
.toNumber();
}
return new BigNumber(num).minus(this.balance).toFormat(2);
},
// 不複投年收益
notCompounded() {
let num = new BigNumber(this.balance)
.times(this.rate)
.div(100)
.toFormat(2);
return num;
}
},
具體代碼
大段的代碼大家肯定看不下去的,是以本人在此貼出源碼位址供大家下載下傳查閱啦
https://gitee.com/tangying_cn/blog_file/blob/master/progress.zip
我的 個人部落格
有空來坐坐
個人部落格
https://www.wangyanan.online