js实现划线
在JavaScript中实现划线效果
使用CSS文本装饰属性
通过CSS的text-decoration属性可以快速实现划线效果,JavaScript只需动态添加类名或修改样式:
element.style.textDecoration = 'line-through';
创建SVG划线元素 需要更复杂的划线控制时,可以用SVG动态创建:
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100%');
svg.setAttribute('height', '2px');
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', '0');
line.setAttribute('y1', '50%');
line.setAttribute('x2', '100%');
line.setAttribute('y2', '50%');
line.setAttribute('stroke', 'black');
svg.appendChild(line);
element.appendChild(svg);
Canvas绘制方法 适合需要动态计算位置的划线场景:

const canvas = document.createElement('canvas');
canvas.width = element.offsetWidth;
canvas.height = 2;
const ctx = canvas.getContext('2d');
ctx.moveTo(0, 1);
ctx.lineTo(canvas.width, 1);
ctx.stroke();
element.appendChild(canvas);
动态伪元素实现 通过JavaScript添加包含伪元素的样式规则:
const style = document.createElement('style');
style.innerHTML = `.underlined::after {
content: '';
display: block;
width: 100%;
height: 1px;
background: currentColor;
}`;
document.head.appendChild(style);
element.classList.add('underlined');
跨元素划线处理 当需要跨多个DOM元素划线时:

function drawCrossingLine(elements) {
const container = document.createElement('div');
container.style.position = 'relative';
const line = document.createElement('div');
line.style.position = 'absolute';
line.style.height = '1px';
line.style.backgroundColor = '#000';
line.style.top = '50%';
line.style.left = '0';
line.style.width = '100%';
elements.forEach(el => {
el.style.position = 'relative';
el.style.zIndex = '1';
});
container.append(...elements, line);
return container;
}
响应式划线位置调整 根据文本基线自动调整划线位置:
function smartUnderline(element) {
const rect = element.getBoundingClientRect();
const fontSize = parseFloat(getComputedStyle(element).fontSize);
const baseline = rect.bottom - (fontSize * 0.25);
const line = document.createElement('div');
line.style.position = 'absolute';
line.style.bottom = `${rect.bottom - baseline}px`;
line.style.left = '0';
line.style.width = '100%';
line.style.height = '1px';
line.style.backgroundColor = 'currentColor';
element.style.position = 'relative';
element.appendChild(line);
}
动画划线效果 实现从左到右的划线动画:
element.style.position = 'relative';
const underline = document.createElement('div');
underline.style.position = 'absolute';
underline.style.bottom = '0';
underline.style.left = '0';
underline.style.width = '0';
underline.style.height = '2px';
underline.style.backgroundColor = 'blue';
underline.style.transition = 'width 0.3s ease';
element.appendChild(underline);
setTimeout(() => underline.style.width = '100%', 50);
选择具体实现方式时应考虑浏览器兼容性、性能需求以及划线样式的复杂程度。CSS文本装饰方案最简单高效,而Canvas和SVG方案则提供更多自定义控制选项。






