![](/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.