js实现胶囊形状
使用 CSS 和 SVG 实现胶囊形状
胶囊形状可以通过 CSS 的 border-radius 属性或 SVG 的路径绘制实现。以下是两种常见方法:
方法一:纯 CSS 实现
通过设置 border-radius 为高度的一半,可以创建胶囊形状:
.capsule {
width: 100px;
height: 50px;
background-color: #4CAF50;
border-radius: 25px; /* 高度的一半 */
}
方法二:SVG 实现
使用 SVG 的 <rect> 元素结合 rx 和 ry 属性:
<svg width="100" height="50">
<rect x="0" y="0" width="100" height="50" rx="25" ry="25" fill="#4CAF50" />
</svg>
动态调整胶囊形状的 JavaScript 实现
如果需要通过 JavaScript 动态创建或调整胶囊形状,可以参考以下代码:
// 创建 CSS 胶囊元素
function createCssCapsule(width, height, color) {
const capsule = document.createElement('div');
capsule.style.width = `${width}px`;
capsule.style.height = `${height}px`;
capsule.style.backgroundColor = color;
capsule.style.borderRadius = `${height / 2}px`;
return capsule;
}
// 创建 SVG 胶囊元素
function createSvgCapsule(width, height, color) {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', width);
svg.setAttribute('height', height);
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', 0);
rect.setAttribute('y', 0);
rect.setAttribute('width', width);
rect.setAttribute('height', height);
rect.setAttribute('rx', height / 2);
rect.setAttribute('ry', height / 2);
rect.setAttribute('fill', color);
svg.appendChild(rect);
return svg;
}
// 使用示例
document.body.appendChild(createCssCapsule(120, 60, '#FF5722'));
document.body.appendChild(createSvgCapsule(150, 75, '#2196F3'));
响应式胶囊形状
如果需要胶囊形状随容器大小变化,可以使用 CSS 的百分比单位:
.responsive-capsule {
width: 50%;
height: 0;
padding-bottom: 25%; /* 保持宽高比 2:1 */
background-color: #9C27B0;
border-radius: 12.5%; /* 高度的一半 */
}
带边框的胶囊形状
为胶囊添加边框时,注意调整 border-radius 值:
.capsule-with-border {
width: 120px;
height: 60px;
background-color: #FFFFFF;
border: 3px solid #3F51B5;
border-radius: 30px; /* (高度 + 边框宽度) / 2 */
}
这些方法可以根据具体需求选择使用,CSS 方案适合简单场景,SVG 方案更适合需要精细控制的情况。

