如何使用JavaScript修改有序列表::marker伪元素的样式?
解决方案
伪元素不属于真实DOM节点,仅存在于CSS渲染层,所以你没法直接通过DOM元素的style对象修改伪元素的样式,这是你之前尝试的写法全部不生效的核心原因。
以下是两种符合要求的实现方案,都不需要增删元素类名:
方案1:直接向现有样式表插入规则
直接调用页面样式表的insertRule方法插入指定样式:
const targetLi = document.getElementById('thelistitem'); // 确保元素存在再执行后续操作 if (targetLi) { const styleSheet = document.styleSheets[0]; // 把样式规则插在样式表末尾,避免被原有规则覆盖 styleSheet.insertRule(`#${targetLi.id}::marker { color: blue; }`, styleSheet.cssRules.length); }
方案2:动态创建样式标签插入
如果当前页面没有引入任何样式表,第一种方案会报错,可以用动态创建style标签的方式实现:
const targetLi = document.getElementById('thelistitem'); if (targetLi) { const customStyle = document.createElement('style'); customStyle.textContent = `#${targetLi.id}::marker { color: blue; }`; document.head.appendChild(customStyle); }
内容的提问来源于stack exchange,提问作者Kitty Craft0
相关产品推荐
相关产品推荐

