JavaScript 设计贷款计算器
贷款计算器可用于根据总贷款金额、还款月数和利率计算每月还款额。
方法: 方法非常简单,我们将从用户那里获取3个输入,即金额(总贷款金额)、利率(利率)和月数(还款月数)。根据这三个值,我们可以计算出总金额。最后,我们将显示总金额。
公式:
interest = (amount * (rate * 0.01))/months;
total = ((amount/months) + interest);
使用HTML,我们正在设计简单的结构,并使用CSS(内部CSS)进行样式设置。在输入时,我们调用 calculate() 函数并显示结果。calculate()函数使用HTML属性 onchange 来接收输入(当元素的值发生改变时,onchange属性将触发)。
前提条件: HTML,CSS和JavaScript的基本概念。
示例: 我们将创建两个分离的文件,即HTML和JavaScript,并将JavaScript文件链接到HTML文件中。
- HTML -(index.html):用于创建贷款计算器的基本结构
- CSS – 用于设计贷款计算器
- JavaScript -(app.js):用于实现公式
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Loan Calculator</title>
<style>
body {
background-color: yellow;
font-family: 'Trebuchet MS';
}
h1 {
font-size: 35px;
}
h1 {
font-size: 21px;
margin-top: 20px;
}
.calculator {
width: 400px;
height: 450px;
background-color: black;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
padding: 20px 0px 0px 100px;
border-radius: 50px;
color: white;
}
input {
padding: 7px;
width: 70%;
margin-top: 7px;
}
</style>
</head>
<body>
<div class="calculator">
<h1>Loan Calculator</h1>
<!-- Calling Calculate function defined in app.js -->
<p>Amount (₹) :
<input id="amount" type="number"
onchange="Calculate()">
</p>
<p>Interest Rate :
<input id="rate" type="number"
onchange="Calculate()">
</p>
<p>Months to Pay :
<input id="months" type="number"
onchange="Calculate()">
</p>
<h2 id="total"></h2>
</div>
<script src="app.js"></script>
</body>
</html>
CSS代码
body {
background-color: yellow;
font-family: 'Trebuchet MS';
}
h1 {
font-size: 35px;
}
h1 {
font-size: 21px;
margin-top: 20px;
}
.calculator {
width: 400px;
height: 450px;
background-color: black;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
padding: 20px 0px 0px 100px;
border-radius: 50px;
color: white;
}
input {
padding: 7px;
width: 70%;
margin-top: 7px;
}
Javascript代码
function Calculate() {
// Extracting value in the amount
// section in the variable
const amount = document.querySelector("#amount").value;
// Extracting value in the interest
// rate section in the variable
const rate = document.querySelector("#rate").value;
// Extracting value in the months
// section in the variable
const months = document.querySelector("#months").value;
// Calculating interest per month
const interest = (amount * (rate * 0.01)) / months;
// Calculating total payment
const total = ((amount / months) + interest).toFixed(2);
document.querySelector("#total")
.innerHTML = "EMI : (₹)" + total;
}
输出:

极客教程