此文为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