简体   繁体   English

你可以在 javascript 中设置有序列表编号的样式吗? 如果是这样,如何?

[英]Can you style ordered list numbers in javascript? If so, how?

Lets say you have an HTML element like so:假设您有一个像这样的 HTML 元素:

<p id="theparagraph">Hello there!</p>

You can style it by using CSS or javascript, respectively, like so:您可以分别使用 CSS 或 javascript 设置样式,如下所示:

#theparagraph{
  color:green;
}
document.getElementById("theparagraph").style="color:blue";

It has come to my attention that, with an ordered list, you can style the "marker" attribute (or whatever it is called).我注意到,使用有序列表,您可以设置“标记”属性(或任何名称)的样式。 This is the individual number that comes before the text of an ordered list item.这是位于有序列表项文本之前的单个编号。 Here is an example:下面是一个例子:

<ol>
  <li id="thelistitem">
    Hello there!
  </li>
</ol>

You can style it in CSS by doing the following:您可以通过执行以下操作在 CSS 中设置样式:

#thelistitem{
  color:blue;
}
#thelistitem::marker{
  color:red;
}

But, my question is, what is the equivalant for that in javascript?但是,我的问题是,javascript 中的等效项是什么? I have tried the following, with no success:我尝试了以下方法,但没有成功:

document.getElementById("thelistitem").style="::marker{color:blue}";
document.getElementById("thelistitem").style::marker="color:blue";
document.getElementById("thelistitem").style.marker="color:blue";

None of them have worked.他们都没有工作。 What DOES work?有什么作用? And I am not asking for a class that is assigned and taken away from elements.而且我不是要求一个从元素中分配和带走的类。 I am asking for the style of it.我问的是它的风格。 How would one edit it?怎么编辑呢?

While JS cannot directly alter the color of the marker as it's a pseudo element, not actually in the DOM, we can get it to set a CSS variable of the actual 'real' element and use that to change the color in the pseudo element.虽然 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 cannot manipulate pseudo elements because they aren't actually presented in the DOM tree, But you can do a workaround to achieve your goal by using CSS Variables ! 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>

We just assigned --custom-variable to color property, and manipulated its value using setProperty in JavaScript for the parent element.我们只是将--custom-variable分配给 color 属性,并在 JavaScript 中使用 setProperty 为父元素操作其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM