如何用CSS实现文本内阴影?避免手动复制文本到data属性
解决文本内阴影无需手动同步文本的方案
首先明确:CSS目前没有原生能力直接读取元素内部文本作为伪元素的content值,要解决手动复制文本到data-text的问题,最实用的是用JavaScript自动同步内容,也可尝试兼容性稍弱的纯CSS方案。
方案一:JavaScript自动同步文本到属性
不用手动在HTML中写data-text,通过JS自动获取元素文本并设置到属性,保持HTML结构简洁:
代码实现
<h1 class="inner-text-shadow">Inset shadow</h1>
.inner-text-shadow { font-size: 10rem; font-family: "Lucida Console", "Courier New", monospace; color: hsla(0, 0%, 13%, 1); position: relative; } .inner-text-shadow::after { content: attr(data-text); width: 100%; height: 100%; position: absolute; top: 5px; left: 5px; color: #FFF; text-shadow: 0px 0px 5px #FFF; mix-blend-mode: overlay; }
// 页面加载后同步所有目标元素的文本到data-text属性 document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.inner-text-shadow').forEach(el => { el.setAttribute('data-text', el.textContent.trim()); }); });
如果文本内容会动态变化,可监听元素内容变化实时更新:
// 监听文本变化(针对动态更新场景) const observer = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.type === 'characterData' || mutation.type === 'childList') { const el = mutation.target.closest('.inner-text-shadow'); if (el) el.setAttribute('data-text', el.textContent.trim()); } }); }); document.querySelectorAll('.inner-text-shadow').forEach(el => { observer.observe(el, { characterData: true, childList: true, subtree: true }); });
方案二:纯CSS内阴影(无文本重复,但兼容性有限)
若不想用JS,可尝试clip-path: text实现内阴影,避免浅色阴影溢出:
.inner-text-shadow { font-size: 10rem; font-family: "Lucida Console", "Courier New", monospace; color: hsla(0, 0%, 13%, 1); position: relative; } .inner-text-shadow::before { content: ''; position: absolute; top: 5px; left: 5px; width: 100%; height: 100%; background: #FFF; filter: blur(5px); mix-blend-mode: overlay; /* 仅webkit内核浏览器支持稳定,Firefox需启用实验性特性 */ -webkit-clip-path: text(alpha); clip-path: text(alpha); }
注意:
clip-path: text目前仅在Chrome、Edge等webkit内核浏览器支持稳定,Firefox需要开启layout.css.clip-path-text.enabled实验性开关,兼容性不如JS方案。
内容的提问来源于stack exchange,提问作者lllKoMaHDoRlll
相关产品推荐
相关产品推荐

