场景引入:
刚接手公司后台管理系统,产品经理指着用户评论区的"原价"要求:"这里得加个删除线,旁边显示折后价!"——这种需求太常见了!今天咱们就彻底搞懂CSS删除线,顺便教你用JS动态控制的小妙招。
text-decoration
最正统写法.discount { text-decoration: line-through; /* 关键属性 */ color: #999; /* 通常搭配灰色 */ }
特点:
underline overline line-through
能同时出现 <del>
标签语义化写法原价:<del>299元</del> 现价:199元
适用场景:
<span>
更语义化 .custom-line { position: relative; display: inline-block; } .custom-line::after { content: ""; position: absolute; left: 0; top: 50%; width: 100%; height: 2px; background: red; transform: rotate(-5deg); /* 倾斜效果 */ }
适用场景:
.special-line { text-decoration: line-through; text-decoration-thickness: 2px; /* 控制粗细 */ text-decoration-color: #ff0000; /* 单独改颜色 */ }
注意:
thickness
属性较新(2025年主流浏览器已全面支持) border-bottom
模拟 // 原生JS操作 const price = document.getElementById('oldPrice'); price.style.textDecoration = 'line-through'; // 添加 price.style.textDecoration = 'none'; // 移除 // jQuery写法(如果项目在用) $('#oldPrice').css('text-decoration', 'line-through');
document.querySelector('.toggle-btn').addEventListener('click', () => { const text = document.querySelector('.target-text'); text.classList.toggle('cross-out'); }); /* CSS配合 */ .cross-out { text-decoration: line-through; opacity: 0.6; }
移动端适配问题:
部分安卓机型对text-decoration-style: dashed
(虚线删除线)支持较差,建议用伪元素模拟
打印样式优化:
@media print { .print-line { text-decoration: line-through !important; } }
无障碍访问:
使用<del>
时建议搭配aria-label
:
<del aria-label="原价已失效">$99</del>
最新趋势(2025年):
text-decoration
新增skip-spaces
属性,可以控制删除线是否跳过空格 background-clip:text
实现 下次产品经理再提删除线需求,你可以自信地说:"这个效果,我有至少5种实现方案!" 🎯
本文由 进芳洲 于2025-07-30发表在【云服务器提供商】,文中图片由(进芳洲)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://up.7tqx.com/wenda/488486.html
发表评论