你可以样式有序的列表数字在javascript?如果有,怎么做?



假设你有一个这样的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中,但我们可以让它为实际的'real'元素设置一个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-variablecolor属性,并在JavaScript中为父元素使用setProperty来操纵它的值。