js实现徽章
实现徽章的方法
使用HTML和CSS创建徽章的基础结构,JavaScript用于动态更新徽章内容或样式。
<div class="badge" id="badge">5</div>
.badge {
position: relative;
display: inline-block;
width: 20px;
height: 20px;
background-color: red;
color: white;
border-radius: 50%;
text-align: center;
line-height: 20px;
font-size: 12px;
}
// 更新徽章内容
document.getElementById('badge').textContent = '10';
动态创建徽章
通过JavaScript动态创建徽章元素并添加到DOM中。
const badge = document.createElement('div');
badge.className = 'badge';
badge.textContent = 'New';
document.body.appendChild(badge);
通知徽章实现
在导航菜单或图标上添加通知数量的徽章。
<button id="notifications">
Notifications
<span class="badge">3</span>
</button>
// 更新通知数量
const updateBadge = count => {
document.querySelector('#notifications .badge').textContent = count;
};
updateBadge(5);
SVG徽章实现
使用SVG创建更复杂的徽章图形。
<svg width="24" height="24" id="svg-badge">
<circle cx="12" cy="12" r="10" fill="red"/>
<text x="12" y="16" text-anchor="middle" fill="white" font-size="12">8</text>
</svg>
// 更新SVG徽章
document.querySelector('#svg-badge text').textContent = '12';
动画徽章效果
为徽章添加CSS动画效果吸引注意力。
.badge-pulse {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
// 添加动画类
document.getElementById('badge').classList.add('badge-pulse');






