![](/img/trans.png)
[英]How can I have numbers with a custom format in an ordered list in HTML?
[英]Can you style ordered list numbers in javascript? If so, how?
假设您有一个像这样的 HTML 元素:
<p id="theparagraph">Hello there!</p>
您可以分别使用 CSS 或 javascript 设置样式,如下所示:
#theparagraph{
color:green;
}
document.getElementById("theparagraph").style="color:blue";
我注意到,使用有序列表,您可以设置“标记”属性(或任何名称)的样式。 这是位于有序列表项文本之前的单个编号。 下面是一个例子:
<ol>
<li id="thelistitem">
Hello there!
</li>
</ol>
您可以通过执行以下操作在 CSS 中设置样式:
#thelistitem{
color:blue;
}
#thelistitem::marker{
color:red;
}
但是,我的问题是,javascript 中的等效项是什么? 我尝试了以下方法,但没有成功:
document.getElementById("thelistitem").style="::marker{color:blue}";
document.getElementById("thelistitem").style::marker="color:blue";
document.getElementById("thelistitem").style.marker="color:blue";
他们都没有工作。 有什么作用? 而且我不是要求一个从元素中分配和带走的类。 我问的是它的风格。 怎么编辑呢?
虽然 JS 不能直接改变标记的颜色,因为它是一个伪元素,实际上不在 DOM 中,我们可以让它设置实际“真实”元素的 CSS 变量,并使用它来更改伪元素中的颜色。
#thelistitem { color: blue; } #thelistitem::marker { color: var(--color); }
<ol> <li id="thelistitem"> Hello there! </li> </ol> <button onclick="document.getElementById('thelistitem').style.setProperty('--color', 'red');">Click me</button>
JavaScript 无法操作伪元素,因为它们实际上并未出现在 DOM 树中,但是您可以通过使用CSS 变量来实现您的目标!
ol li { color: #777; } ol li::marker { color: var(--custom-variable); }
<ol> <li id="list_item">List Item 1</li> </ol> <button onclick="document.getElementById('list_item').style.setProperty('--custom-variable', '#000');"> Change Color </button>
我们只是将--custom-variable分配给 color 属性,并在 JavaScript 中使用 setProperty 为父元素操作其值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.