具体的代码是以下,可以看到
<div id="crypto-price-widget">
<p class="loading">Loading cryptocurrency prices... <span class="spinner"></span></p>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const apiUrl = '/proxy.php'; // 指向你的proxy脚本
const container = document.getElementById('crypto-price-widget');
if (!container) {
console.error('Element with ID "crypto-price-widget" not found.');
return;
}
// 定义币种图标映射表
const iconMap = {
'btc': 'https://bqbot.cn/wp-content/themes/onenav/images/BZ/BTC.svg',
'eth': 'https://bqbot.cn/wp-content/themes/onenav/images/BZ/ETH.svg',
'doge': 'https://bqbot.cn/wp-content/themes/onenav/images/BZ/DOGE.svg',
'bnb': 'https://bqbot.cn/wp-content/themes/onenav/images/BZ/BNB.svg',
'sol': 'https://bqbot.cn/wp-content/themes/onenav/images/BZ/SOL.svg',
};
// 定义币种排序优先级
const priorityOrder = ['btc', 'eth', 'sol', 'bnb', 'doge'];
// 定义更新价格的函数
function updatePrices() {
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.code === 0 && data.data) {
// 去掉 USDT 后缀,并按优先级排序
const sortedData = data.data
.map(item => {
const symbol = item.symbol.toLowerCase().replace('usdt', '');
return { ...item, symbol };
})
.sort((a, b) => {
const aPriority = priorityOrder.indexOf(a.symbol.toLowerCase());
const bPriority = priorityOrder.indexOf(b.symbol.toLowerCase());
return aPriority - bPriority;
});
let html = '<ul>';
sortedData.forEach(item => {
const price = parseFloat(item.price).toFixed(2);
const rate = (parseFloat(item.rate_24h) * 100).toFixed(2);
const trendClass = item.is_up ? 'up' : 'down';
const trendSymbol = item.is_up ? '↑ 涨' : '↓ 跌'; // 方向符号
// 获取币种图标 URL
const iconUrl = iconMap[item.symbol.toLowerCase()] || ''; // 如果找不到对应图标,则为空
// 动态生成 HTML
html += `
<li>
<span class="currency-icon">
${iconUrl ? `<img src="${iconUrl}" alt="${item.symbol.toUpperCase()} Icon" />` : ''}
</span>
<span class="currency-name">${item.symbol.toUpperCase()}</span>
<span class="price">$${price}</span>
<span class="trend ${trendClass}">${rate}% ${trendSymbol}</span>
</li>`;
});
html += '</ul>';
container.innerHTML = html;
// 更新时间戳
updateTimestamp();
} else {
container.innerHTML = '<p style="color: red;">无法加载加密货币价格,请检查网络连接或稍后再试。</p>';
}
})
.catch(error => {
console.error('API Error:', error);
container.innerHTML = '<p style="color: red;">无法加载加密货币价格,请检查网络连接或稍后再试。</p>';
});
}
// 更新时间戳
function updateTimestamp() {
const timestamp = document.getElementById('timestamp');
if (!timestamp) {
const newTimestamp = document.createElement('p');
newTimestamp.id = 'timestamp';
newTimestamp.style.fontSize = '12px';
newTimestamp.style.color = '#666';
container.appendChild(newTimestamp);
}
document.getElementById('timestamp').textContent = `上次更新时间:${new Date().toLocaleTimeString()}`;
}
// 每隔 30 秒更新一次价格
updatePrices(); // 初始化加载
setInterval(updatePrices, 30000); // 每 30 秒调用一次
});
</script>
<style>
/* 主容器样式 */
#crypto-price-widget {
background: linear-gradient(135deg, #f9f9f9, #e0e0ff); /* 渐变背景 */
border: 2px solid #9b8080; /* 红色边框 */
padding: 15px;
font-family: Arial, sans-serif;
font-size: 14px;
color: #333333; /* 文字颜色 */
border-radius: 8px; /* 圆角 */
max-width: 400px; /* 最大宽度 */
margin: 0 auto; /* 居中 */
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}
/* 列表样式 */
#crypto-price-widget ul {
list-style: none;
padding: 0;
margin: 0;
}
/* 列表项样式 */
#crypto-price-widget li {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
padding: 8px;
border-bottom: 1px solid #ddd; /* 分割线 */
}
#crypto-price-widget li:last-child {
border-bottom: none; /* 去掉最后一项的分割线 */
}
/* 币种图标样式 */
#crypto-price-widget .currency-icon img {
width: 24px; /* 图标大小 */
height: 24px;
margin-right: 8px; /* 图标与文字之间的间距 */
vertical-align: middle;
}
/* 货币名称样式 */
#crypto-price-widget .currency-name {
font-weight: bold;
color: #007bff; /* 蓝色文字 */
margin-right: 8px;
margin-left: -20px;
}
/* 价格样式 */
#crypto-price-widget .price {
color: #28a745; /* 绿色文字 */
font-weight: bold;
}
/* 上涨样式 */
#crypto-price-widget .trend.up {
color: #28a745; /* 绿色 */
font-weight: bold;
}
/* 下跌样式 */
#crypto-price-widget .trend.down {
color: #dc3545; /* 红色 */
font-weight: bold;
}
/* 加载动画 */
.loading .spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid #007bff;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* 响应式设计 */
@media (max-width: 600px) {
#crypto-price-widget {
font-size: 12px;
}
#crypto-price-widget li {
flex-direction: column;
align-items: flex-start;
}
#crypto-price-widget .price,
#crypto-price-widget .trend {
margin-top: 5px;
}
/* 小屏幕下的分割线 */
#crypto-price-widget li {
padding: 5px 0;
}
}
</style>
上面的代码可以看到,我是用了proxy的,。
proxy.php
<?php
// proxy.php
// 设置目标 API URL
$apiUrl = '你的获取币价的接口url,这需要你自己提供';
// 使用 file_get_contents 获取 API 数据
$response = file_get_contents($apiUrl);
// 设置响应头为 JSON 格式
header('Content-Type: application/json');
// 输出 API 响应
echo $response;
然后我的接口返回的json是这样的
{"code":0,"data":[{"name":"bnbusdt","symbol":"bnbusdt","price":"621.69","rate_24h":"0.004611172486670822","is_up":0},{"name":"btcusdt","symbol":"btcusdt","price":"87281.51","rate_24h":"0.0062835138609466","is_up":1},{"name":"ethusdt","symbol":"ethusdt","price":"2018.74","rate_24h":"0.0036092827172032487","is_up":1},{"name":"htxusdt","symbol":"htxusdt","price":"1.659E-6","rate_24h":"0.011585365853658504","is_up":1},{"name":"solusdt","symbol":"solusdt","price":"137.9817","rate_24h":"0.00875215517241379","is_up":0}]}
拿着这样的接口数据,我就能在我的前端去展示了
具体演示可以看bqbot.cn