房贷利率计算前端小程序

利率计算前端小程序


视图效果展示如下:
在这里插入图片描述

在这里插入代码片
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贷款计算器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#f97316',
                        neutral: '#f8fafc',
                        dark: '#1e293b'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            }
            .btn-hover {
                transition: all 0.3s ease;
            }
            .btn-hover:hover {
                transform: translateY(-2px);
                box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.4);
            }
            .input-focus {
                transition: all 0.2s ease;
            }
            .input-focus:focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
            }
            .fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa-solid fa-calculator text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-dark">贷款计算器</h1>
            </div>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="#" class="text-gray-600 hover:text-primary transition-colors">首页</a></li>
                    <li><a href="#" class="text-gray-600 hover:text-primary transition-colors">贷款指南</a></li>
                    <li><a href="#" class="text-gray-600 hover:text-primary transition-colors">联系我们</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8">
        <!-- 介绍部分 -->
        <section class="mb-10 text-center max-w-3xl mx-auto">
            <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4 text-dark">海内存知己天涯若比邻</h2>
            <p class="text-gray-600 text-lg">输入贷款信息,选择还款方式,立即获取详细的还款计划,帮助您更好地规划财务。</p>
        </section>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 表单部分 -->
            <section class="lg:col-span-1 bg-white rounded-xl p-6 card-shadow fade-in">
                <h3 class="text-xl font-bold mb-6 text-dark flex items-center">
                    <i class="fa-solid fa-pencil-square text-primary mr-2"></i>贷款信息
                </h3>
                <form id="loanForm" class="space-y-5">
                    <div class="space-y-2">
                        <label for="loanAmount" class="block text-sm font-medium text-gray-700">贷款金额 (元)</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-money-bill-wave"></i>
                            </span>
                            <input type="number" id="loanAmount" name="loanAmount" min="1" step="any" 
                                class="pl-10 w-full rounded-lg border-gray-300 shadow-sm input-focus py-3 px-4 border focus:outline-none" 
                                placeholder="请输入贷款金额" required>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label for="loanTerm" class="block text-sm font-medium text-gray-700">贷款年限</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-calendar"></i>
                            </span>
                            <input type="number" id="loanTerm" name="loanTerm" min="1" max="30" step="any" 
                                class="pl-10 w-full rounded-lg border-gray-300 shadow-sm input-focus py-3 px-4 border focus:outline-none" 
                                placeholder="请输入贷款年限" required>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label for="interestRate" class="block text-sm font-medium text-gray-700">贷款利率 (%)</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-percent"></i>
                            </span>
                            <input type="number" id="interestRate" name="interestRate" min="0.01" step="0.01" 
                                class="pl-10 w-full rounded-lg border-gray-300 shadow-sm input-focus py-3 px-4 border focus:outline-none" 
                                placeholder="请输入年利率" required>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label for="repaymentType" class="block text-sm font-medium text-gray-700">还款方式</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-list-ul"></i>
                            </span>
                            <select id="repaymentType" name="repaymentType" 
                                class="pl-10 w-full rounded-lg border-gray-300 shadow-sm input-focus py-3 px-4 border focus:outline-none appearance-none bg-white">
                                <option value="equal-principal-interest">等额本息</option>
                                <option value="equal-principal">等额本金</option>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-500">
                                <i class="fa-solid fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <label for="timeUnit" class="block text-sm font-medium text-gray-700">还款周期</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-500">
                                <i class="fa-solid fa-clock"></i>
                            </span>
                            <select id="timeUnit" name="timeUnit" 
                                class="pl-10 w-full rounded-lg border-gray-300 shadow-sm input-focus py-3 px-4 border focus:outline-none appearance-none bg-white">
                                <option value="year">年</option>
                                <option value="month">月</option>
                            </select>
                            <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-gray-500">
                                <i class="fa-solid fa-chevron-down"></i>
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg btn-hover transition-all duration-300 flex items-center justify-center">
                        <i class="fa-solid fa-calculator mr-2"></i>计算还款计划
                    </button>
                </form>
            </section>

            <!-- 结果展示部分 -->
            <section class="lg:col-span-2 bg-white rounded-xl p-6 card-shadow fade-in">
                <h3 class="text-xl font-bold mb-6 text-dark flex items-center">
                    <i class="fa-solid fa-table text-primary mr-2"></i>还款计划
                </h3>
                
                <div id="summary" class="mb-8 bg-blue-50 rounded-lg p-5 border-l-4 border-primary hidden">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="text-center">
                            <p class="text-sm text-gray-600 mb-1">贷款总额</p>
                            <p class="text-xl font-bold text-dark" id="totalLoanAmount">¥0.00</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm text-gray-600 mb-1">总支付利息</p>
                            <p class="text-xl font-bold text-dark" id="totalInterest">¥0.00</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm text-gray-600 mb-1">还款总额</p>
                            <p class="text-xl font-bold text-dark" id="totalPayment">¥0.00</p>
                        </div>
                    </div>
                </div>

                <div id="paymentScheduleContainer" class="overflow-x-auto">
                    <table id="paymentSchedule" class="min-w-full divide-y divide-gray-200 hidden">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">期数</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">还款本金</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">还款利息</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">还款总额</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="paymentScheduleBody">
                            <!-- 表格内容将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>

                <div id="noResult" class="py-16 text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-blue-100 mb-4">
                        <i class="fa-solid fa-calculator text-primary text-2xl"></i>
                    </div>
                    <h4 class="text-lg font-medium text-gray-900 mb-2">请输入贷款信息并计算</h4>
                    <p class="text-gray-500 max-w-md mx-auto">填写左侧表单并点击"计算还款计划"按钮,即可查看详细的还款计划</p>
                </div>
            </section>
        </div>
    </main>

    <footer class="bg-dark text-white py-8 mt-10">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div>
                    <h3 class="text-lg font-bold mb-4">贷款计算器</h3>
                    <p class="text-gray-400">帮助您轻松计算各种贷款的还款计划,做出明智的财务决策。</p>
                </div>
                <div>
                    <h3 class="text-lg font-bold mb-4">快速链接</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">首页</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">贷款指南</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">联系我们</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-bold mb-4">联系我们</h3>
                    <ul class="space-y-2">
                        <li class="flex items-center">
                            <i class="fa-solid fa-envelope text-primary mr-2"></i>
                            <a href="mailto:support@loancalculator.com" class="text-gray-400 hover:text-white transition-colors">support@loancalculator.com</a>
                        </li>
                        <li class="flex items-center">
                            <i class="fa-solid fa-phone text-primary mr-2"></i>
                            <a href="tel:+8612345678901" class="text-gray-400 hover:text-white transition-colors">+86 123 4567 8901</a>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="border-t border-gray-800 mt-8 pt-8 text-center text-gray-400">
                <p>&copy; 2025 贷款计算器 版权所有</p>
            </div>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const loanForm = document.getElementById('loanForm');
            const paymentSchedule = document.getElementById('paymentSchedule');
            const paymentScheduleBody = document.getElementById('paymentScheduleBody');
            const summary = document.getElementById('summary');
            const noResult = document.getElementById('noResult');
            const totalLoanAmount = document.getElementById('totalLoanAmount');
            const totalInterest = document.getElementById('totalInterest');
            const totalPayment = document.getElementById('totalPayment');

            loanForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 获取表单值
                const loanAmount = parseFloat(document.getElementById('loanAmount').value);
                const loanTerm = parseFloat(document.getElementById('loanTerm').value);
                const interestRate = parseFloat(document.getElementById('interestRate').value);
                const repaymentType = document.getElementById('repaymentType').value;
                const timeUnit = document.getElementById('timeUnit').value;

                // 计算还款计划
                let schedule = [];
                let totalInterestAmount = 0;
                
                if (repaymentType === 'equal-principal-interest') {
                    // 等额本息
                    [schedule, totalInterestAmount] = calculateEqualPrincipalInterest(loanAmount, loanTerm, interestRate, timeUnit);
                } else {
                    // 等额本金
                    [schedule, totalInterestAmount] = calculateEqualPrincipal(loanAmount, loanTerm, interestRate, timeUnit);
                }

                // 显示结果
                displayResults(schedule, loanAmount, totalInterestAmount);
            });

            // 等额本息计算
            function calculateEqualPrincipalInterest(principal, years, annualRate, timeUnit) {
                const rate = annualRate / 100;
                let periods;
                let ratePerPeriod;
                
                if (timeUnit === 'year') {
                    periods = years;
                    ratePerPeriod = rate;
                } else {
                    periods = years * 12;
                    ratePerPeriod = rate / 12;
                }
                
                // 计算每期还款额
                const payment = principal * ratePerPeriod * Math.pow(1 + ratePerPeriod, periods) / 
                               (Math.pow(1 + ratePerPeriod, periods) - 1);
                
                let schedule = [];
                let remainingPrincipal = principal;
                let totalInterest = 0;
                
                for (let i = 1; i <= periods; i++) {
                    const interest = remainingPrincipal * ratePerPeriod;
                    const principalPayment = payment - interest;
                    remainingPrincipal -= principalPayment;
                    
                    // 最后一期调整可能的浮点数精度问题
                    if (i === periods && Math.abs(remainingPrincipal) < 0.01) {
                        remainingPrincipal = 0;
                    }
                    
                    totalInterest += interest;
                    
                    schedule.push({
                        period: i,
                        principal: principalPayment,
                        interest: interest,
                        total: payment,
                        remaining: remainingPrincipal
                    });
                }
                
                return [schedule, totalInterest];
            }

            // 等额本金计算
            function calculateEqualPrincipal(principal, years, annualRate, timeUnit) {
                const rate = annualRate / 100;
                let periods;
                let ratePerPeriod;
                
                if (timeUnit === 'year') {
                    periods = years;
                    ratePerPeriod = rate;
                } else {
                    periods = years * 12;
                    ratePerPeriod = rate / 12;
                }
                
                const principalPayment = principal / periods;
                let remainingPrincipal = principal;
                let totalInterest = 0;
                let schedule = [];
                
                for (let i = 1; i <= periods; i++) {
                    const interest = remainingPrincipal * ratePerPeriod;
                    const payment = principalPayment + interest;
                    remainingPrincipal -= principalPayment;
                    
                    // 最后一期调整可能的浮点数精度问题
                    if (i === periods && Math.abs(remainingPrincipal) < 0.01) {
                        remainingPrincipal = 0;
                    }
                    
                    totalInterest += interest;
                    
                    schedule.push({
                        period: i,
                        principal: principalPayment,
                        interest: interest,
                        total: payment,
                        remaining: remainingPrincipal
                    });
                }
                
                return [schedule, totalInterest];
            }

            // 显示计算结果
            function displayResults(schedule, principal, totalInterestAmount) {
                // 清空表格
                paymentScheduleBody.innerHTML = '';
                
                // 显示结果区域,隐藏无结果提示
                paymentSchedule.classList.remove('hidden');
                summary.classList.remove('hidden');
                noResult.classList.add('hidden');
                
                // 填充表格
                schedule.forEach(payment => {
                    const row = document.createElement('tr');
                    row.className = 'hover:bg-gray-50 transition-colors';
                    
                    // 添加动画延迟
                    row.style.animation = `fadeIn 0.5s ease-in-out ${payment.period * 0.05}s forwards`;
                    row.style.opacity = '0';
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${payment.period}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥${payment.principal.toFixed(2)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥${payment.interest.toFixed(2)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-primary">¥${payment.total.toFixed(2)}</td>
                    `;
                    
                    paymentScheduleBody.appendChild(row);
                });
                
                // 更新摘要信息
                totalLoanAmount.textContent = `¥${principal.toFixed(2)}`;
                totalInterest.textContent = `¥${totalInterestAmount.toFixed(2)}`;
                totalPayment.textContent = `¥${(principal + totalInterestAmount).toFixed(2)}`;
                
                // 滚动到结果区域
                paymentSchedule.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    </script>
</body>
</html>

这里是版本二:视图效果如下
在这里插入图片描述
下面是源码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>贷款计算器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
        }
        .input-group {
            margin: 10px 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        input, select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        table {
            width: 100%;
            margin-top: 20px;
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <div class="input-group">
        <label>贷款金额:</label>
        <input type="number" id="amount" placeholder="元">
        
        <label>贷款年限:</label>
        <input type="number" id="years" placeholder="年">
        
        <label>贷款利率:</label>
        <input type="number" id="rate" placeholder="%" step="0.01">
        
        <select id="method">
            <option value="equalPrincipalAndInterest">等额本息</option>
            <option value="equalPrincipal">等额本金</option>
        </select>
        
        <select id="unit">
            <option value="year">按年显示</option>
            <option value="month">按月显示</option>
        </select>
        
        <button onclick="calculate()">计算</button>
    </div>

    <table id="resultTable">
        <thead>
            <tr>
                <th>期数</th>
                <th>还款本金</th>
                <th>还款利息</th>
                <th>还款总额</th>
            </tr>
        </thead>
        <tbody id="resultBody">
        </tbody>
    </table>

    <script>
        function calculate() {
            // 获取输入值
            const amount = parseFloat(document.getElementById('amount').value);
            const years = parseFloat(document.getElementById('years').value);
            const rate = parseFloat(document.getElementById('rate').value) / 100;
            const method = document.getElementById('method').value;
            const unit = document.getElementById('unit').value;

            // 输入验证
            if (!amount || !years || !rate) {
                alert('请输入完整有效的数值');
                return;
            }

            // 计算总月数
            const totalMonths = years * 12;
            let results = [];

            if (method === 'equalPrincipalAndInterest') {
                // 等额本息计算
                const monthlyRate = rate / 12;
                const monthlyPayment = (amount * monthlyRate * Math.pow(1 + monthlyRate, totalMonths)) 
                                    / (Math.pow(1 + monthlyRate, totalMonths) - 1);
                let remaining = amount;

                for (let i = 1; i <= totalMonths; i++) {
                    const interest = remaining * monthlyRate;
                    const principal = monthlyPayment - interest;
                    remaining -= principal;
                    results.push({
                        principal: principal,
                        interest: interest,
                        total: principal + interest
                    });
                }
            } else {
                // 等额本金计算
                const monthlyPrincipal = amount / totalMonths;
                let remaining = amount;

                for (let i = 1; i <= totalMonths; i++) {
                    const interest = remaining * rate / 12;
                    remaining -= monthlyPrincipal;
                    results.push({
                        principal: monthlyPrincipal,
                        interest: interest,
                        total: monthlyPrincipal + interest
                    });
                }
            }

            // 处理显示单位
            const displayResults = [];
            if (unit === 'year') {
                // 按年汇总
                for (let year = 0; year < years; year++) {
                    let yearPrincipal = 0;
                    let yearInterest = 0;
                    for (let month = 0; month < 12; month++) {
                        const index = year * 12 + month;
                        if (index >= results.length) break;
                        yearPrincipal += results[index].principal;
                        yearInterest += results[index].interest;
                    }
                    displayResults.push({
                        principal: yearPrincipal,
                        interest: yearInterest,
                        total: yearPrincipal + yearInterest
                    });
                }
            } else {
                // 直接使用月度数据
                displayResults.push(...results);
            }

            // 显示结果
            const tbody = document.getElementById('resultBody');
            tbody.innerHTML = '';
            displayResults.forEach((item, index) => {
                const row = `<tr>
                    <td>${index + 1}</td>
                    <td>${item.principal.toFixed(2)}</td>
                    <td>${item.interest.toFixed(2)}</td>
                    <td>${item.total.toFixed(2)}</td>
                </tr>`;
                tbody.innerHTML += row;
            });
        }
    </script>
</body>
</html>

完结!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值