js实现徽章
实现徽章的基本方法
使用HTML和CSS创建徽章的基础结构,通过JavaScript动态添加或修改徽章内容。以下是一个简单示例:
<div class="badge-container">
<span class="badge">1</span>
</div>
.badge {
position: absolute;
top: -5px;
right: -5px;
background-color: red;
color: white;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
font-size: 12px;
}
// 更新徽章内容
function updateBadge(count) {
const badge = document.querySelector('.badge');
badge.textContent = count;
badge.style.display = count > 0 ? 'flex' : 'none';
}
动态创建徽章
通过JavaScript动态创建徽章元素并附加到目标元素上:

function createBadge(parentElement, count) {
const badge = document.createElement('span');
badge.className = 'badge';
badge.textContent = count;
// 设置父元素为相对定位
parentElement.style.position = 'relative';
// 添加徽章到父元素
parentElement.appendChild(badge);
return badge;
}
使用SVG创建更复杂的徽章
对于需要更复杂样式的徽章,可以使用SVG:

function createSVGBadge(parentElement, text) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute('cx', '12');
circle.setAttribute('cy', '12');
circle.setAttribute('r', '10');
circle.setAttribute('fill', 'red');
const textElement = document.createElementNS("http://www.w3.org/2000/svg", "text");
textElement.setAttribute('x', '12');
textElement.setAttribute('y', '16');
textElement.setAttribute('text-anchor', 'middle');
textElement.setAttribute('fill', 'white');
textElement.textContent = text;
svg.appendChild(circle);
svg.appendChild(textElement);
parentElement.appendChild(svg);
return svg;
}
响应式徽章组件
创建一个可重用的徽章组件类:
class Badge {
constructor(options) {
this.element = document.createElement('span');
this.element.className = 'badge';
this.update(options);
}
update({ count, color, position }) {
this.element.textContent = count;
this.element.style.backgroundColor = color || 'red';
if (position) {
this.element.style.top = position.top || '0';
this.element.style.right = position.right || '0';
}
this.element.style.display = count > 0 ? 'block' : 'none';
}
attachTo(parentElement) {
parentElement.style.position = 'relative';
parentElement.appendChild(this.element);
}
}
使用示例
// 创建并附加徽章
const notificationIcon = document.getElementById('notification-icon');
const badge = new Badge({ count: 5, color: 'blue' });
badge.attachTo(notificationIcon);
// 更新徽章
badge.update({ count: 3 });
动画效果
为徽章添加简单的动画效果:
.badge-pulse {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
// 添加脉冲动画
function addPulseAnimation(badgeElement) {
badgeElement.classList.add('badge-pulse');
}






