<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>实时汇率转换器</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Arial', sans-serif;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);min-height: 100vh;display: flex;justify-content: center;align-items: center;padding: 20px;}.container {background: white;border-radius: 15px;box-shadow: 0 20px 40px rgba(0,0,0,0.1);width: 100%;max-width: 500px;overflow: hidden;}.header {background: #4a5568;color: white;padding: 20px;text-align: center;}.header h1 {font-size: 24px;margin-bottom: 5px;}.header p {font-size: 14px;opacity: 0.9;}.converter {padding: 30px;}.input-group {margin-bottom: 20px;}.input-group label {display: block;margin-bottom: 8px;font-weight: bold;color: #4a5568;font-size: 14px;}.input-container {display: flex;gap: 10px;align-items: center;}.amount-input {flex: 1;padding: 12px;border: 2px solid #e2e8f0;border-radius: 8px;font-size: 16px;outline: none;transition: border-color 0.3s ease;}.amount-input:focus {border-color: #667eea;}.currency-select {padding: 12px;border: 2px solid #e2e8f0;border-radius: 8px;font-size: 16px;background: white;cursor: pointer;min-width: 120px;}.currency-select:focus {border-color: #667eea;}.swap-btn {background: #667eea;color: white;border: none;width: 40px;height: 40px;border-radius: 50%;cursor: pointer;font-size: 18px;display: flex;align-items: center;justify-content: center;transition: all 0.3s ease;}.swap-btn:hover {background: #5a67d8;transform: rotate(180deg);}.result {background: #f7fafc;padding: 15px;border-radius: 8px;margin: 20px 0;text-align: center;}.result-value {font-size: 28px;font-weight: bold;color: #2d3748;margin-bottom: 5px;}.result-info {font-size: 14px;color: #718096;}.rate-info {font-size: 14px;color: #718096;text-align: center;margin: 10px 0;}.last-updated {font-size: 12px;color: #a0aec0;text-align: center;margin-top: 10px;}.error {color: #e53e3e;text-align: center;padding: 15px;background: #fee;border-radius: 8px;margin: 10px 0;display: none;}.loading {text-align: center;color: #718096;font-size: 14px;margin: 10px 0;display: none;}.refresh-btn {background: #48bb78;color: white;border: none;padding: 10px 20px;border-radius: 8px;cursor: pointer;font-size: 14px;margin-top: 10px;transition: background 0.3s ease;}.refresh-btn:hover {background: #38a169;}@media (max-width: 480px) {.input-container {flex-direction: column;}.swap-btn {align-self: center;margin: 10px 0;}}</style>
</head>
<body><div class="container"><div class="header">实时汇率转换器<p>准确的货币转换,实时更新</p></div><div class="converter"><div class="input-group"><label for="amount">金额</label><input type="number" id="amount" class="amount-input" placeholder="输入金额" value="1"></div><div class="input-group"><label>从</label><div class="input-container"><input type="text" id="from-amount" class="amount-input" readonly><select id="from-currency" class="currency-select"><option value="USD">美元 (USD)</option><option value="EUR">欧元 (EUR)</option><option value="GBP">英镑 (GBP)</option><option value="JPY">日元 (JPY)</option><option value="CNY">人民币 (CNY)</option><option value="CAD">加元 (CAD)</option><option value="AUD">澳元 (AUD)</option><option value="CHF">瑞士法郎 (CHF)</option><option value="HKD">港元 (HKD)</option><option value="SGD">新加坡元 (SGD)</option></select></div></div><div style="text-align: center; margin: 10px 0;"><button class="swap-btn" id="swap-btn">↻</button></div><div class="input-group"><label>到</label><div class="input-container"><input type="text" id="to-amount" class="amount-input" readonly><select id="to-currency" class="currency-select"><option value="CNY">人民币 (CNY)</option><option value="USD">美元 (USD)</option><option value="EUR">欧元 (EUR)</option><option value="GBP">英镑 (GBP)</option><option value="JPY">日元 (JPY)</option><option value="CAD">加元 (CAD)</option><option value="AUD">澳元 (AUD)</option><option value="CHF">瑞士法郎 (CHF)</option><option value="HKD">港元 (HKD)</option><option value="SGD">新加坡元 (SGD)</option></select></div></div><div id="error" class="error"></div><div id="loading" class="loading">正在获取汇率数据...</div><div class="result"><div id="result-value" class="result-value">0.00</div><div id="result-info" class="result-info">1.00 USD = 7.20 CNY</div></div><div id="rate-info" class="rate-info"></div><div id="last-updated" class="last-updated"></div><div style="text-align: center;"><button id="refresh-btn" class="refresh-btn">刷新汇率</button></div></div></div><script>class CurrencyConverter {constructor() {this.apiKey = 'YOUR_API_KEY'; // 你需要注册一个免费的API密钥this.apiUrl = 'https://api.exchangerate-api.com/v4/latest/USD';this.rates = {};this.lastUpdated = null;this.initElements();this.bindEvents();this.loadRates();}initElements() {this.amountInput = document.getElementById('amount');this.fromCurrency = document.getElementById('from-currency');this.toCurrency = document.getElementById('to-currency');this.fromAmount = document.getElementById('from-amount');this.toAmount = document.getElementById('to-amount');this.resultValue = document.getElementById('result-value');this.resultInfo = document.getElementById('result-info');this.rateInfo = document.getElementById('rate-info');this.lastUpdatedEl = document.getElementById('last-updated');this.errorEl = document.getElementById('error');this.loadingEl = document.getElementById('loading');this.swapBtn = document.getElementById('swap-btn');this.refreshBtn = document.getElementById('refresh-btn');}bindEvents() {// 输入金额变化this.amountInput.addEventListener('input', () => {this.convert();});// 货币选择变化this.fromCurrency.addEventListener('change', () => {this.convert();});this.toCurrency.addEventListener('change', () => {this.convert();});// 交换货币this.swapBtn.addEventListener('click', () => {this.swapCurrencies();});// 刷新汇率this.refreshBtn.addEventListener('click', () => {this.loadRates();});}async loadRates() {try {this.showLoading();this.hideError();// 使用免费的汇率APIconst response = await fetch('https://api.exchangerate-api.com/v4/latest/USD');if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();this.rates = data.rates;this.lastUpdated = new Date(data.timestamp * 1000);this.updateLastUpdated();this.convert();this.hideLoading();} catch (error) {console.error('获取汇率失败:', error);this.showError('无法获取汇率数据,请检查网络连接或稍后重试');this.hideLoading();}}convert() {if (Object.keys(this.rates).length === 0) {this.showError('汇率数据尚未加载');return;}const amount = parseFloat(this.amountInput.value) || 0;const from = this.fromCurrency.value;const to = this.toCurrency.value;if (amount <= 0) {this.updateResult(0, from, to);return;}try {// 计算汇率let fromRate, toRate;if (from === 'USD') {fromRate = 1;} else if (this.rates[from]) {fromRate = this.rates[from];} else {throw new Error(`不支持的货币: ${from}`);}if (to === 'USD') {toRate = 1;} else if (this.rates[to]) {toRate = this.rates[to];} else {throw new Error(`不支持的货币: ${to}`);}// 计算转换后的金额const rate = toRate / fromRate;const convertedAmount = amount * rate;this.updateResult(convertedAmount, from, to);this.updateRateInfo(from, to, rate);} catch (error) {this.showError(error.message);}}updateResult(amount, from, to) {this.fromAmount.value = this.formatAmount(parseFloat(this.amountInput.value) || 0);this.toAmount.value = this.formatAmount(amount);this.resultValue.textContent = this.formatAmount(amount);const fromSymbol = this.getCurrencySymbol(from);const toSymbol = this.getCurrencySymbol(to);this.resultInfo.textContent = `${fromSymbol} ${this.formatAmount(1)} = ${toSymbol} ${this.formatAmount(this.getRate(from, to))}`;}updateRateInfo(from, to, rate) {const fromSymbol = this.getCurrencySymbol(from);const toSymbol = this.getCurrencySymbol(to);this.rateInfo.textContent = `1 ${from} (${fromSymbol}) = ${this.formatAmount(rate)} ${to} (${toSymbol})`;}updateLastUpdated() {if (this.lastUpdated) {this.lastUpdatedEl.textContent = `最后更新: ${this.formatDate(this.lastUpdated)}`;}}getRate(from, to) {if (from === to) return 1;let fromRate, toRate;if (from === 'USD') {fromRate = 1;} else {fromRate = this.rates[from];}if (to === 'USD') {toRate = 1;} else {toRate = this.rates[to];}return toRate / fromRate;}swapCurrencies() {const temp = this.fromCurrency.value;this.fromCurrency.value = this.toCurrency.value;this.toCurrency.value = temp;this.convert();}formatAmount(amount) {return new Intl.NumberFormat('zh-CN', {minimumFractionDigits: 2,maximumFractionDigits: 6}).format(amount);}getCurrencySymbol(currency) {const symbols = {'USD': '$','EUR': '€','GBP': '£','JPY': '¥','CNY': '¥','CAD': 'C$','AUD': 'A$','CHF': 'Fr','HKD': 'HK$','SGD': 'S$'};return symbols[currency] || currency;}formatDate(date) {return date.toLocaleString('zh-CN', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',second: '2-digit'});}showError(message) {this.errorEl.textContent = message;this.errorEl.style.display = 'block';}hideError() {this.errorEl.style.display = 'none';}showLoading() {this.loadingEl.style.display = 'block';}hideLoading() {this.loadingEl.style.display = 'none';}}// 初始化汇率转换器document.addEventListener('DOMContentLoaded', () => {new CurrencyConverter();});// 添加自动刷新功能(每5分钟刷新一次)setInterval(() => {if (window.currencyConverter) {window.currencyConverter.loadRates();}}, 5 * 60 * 1000);</script>
</body>
</html>
主要功能特点:
1. 实时汇率获取
- 使用免费的汇率API获取最新汇率数据
- 自动刷新机制(每5分钟)
2. 用户友好的界面
- 响应式设计,适配移动设备
- 清晰的视觉层次和动画效果
- 错误处理和加载状态
3. 核心功能
- 双向货币转换
- 货币交换按钮
- 实时计算
- 多种货币支持
4. 使用方法
- 直接使用:将代码保存为HTML文件,用浏览器打开
- 自定义API:如果你想使用更专业的API,可以注册以下服务:
- exchangerate-api.com
- fixer.io
- currencyapi.com
5. 扩展功能
你可以添加以下功能:
- 历史汇率图表
- 货币收藏功能
- 离线缓存
- 更多货币支持
- 主题切换