[英]Change li bullet color in js
我有 20 個模板,如下面的代碼所示。 文本是通過數據庫添加的,因此無法更改其中 ul/li 的樣式。 我想編寫 1 個函數來改變它。
是否可以只更改外部 js 文件中的項目符號列表顏色(而不是實際文本)?
<div id="container">
<h1 id="head1">Header</h1>
<p id="p1">
<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
</ul>
</p>
任何幫助將不勝感激。
您可以使用 css 來做到這一點。 您可以使用下面的代碼創建一個類,然后使用 javascript 將該類應用於您需要的項目符號點。
這個例子是由Evan Mulwaski在一個與你類似的問題中提出的。
ul
{
list-style-type: square;
}
ul > li
{
color: green;
}
ul > li > span
{
color: black;
}
這是原始問題的鏈接: 如何設置 ul/li 項目符號點顏色?
要更改項目符號:
使用
list-style-type: "\1F44D"; // thumbs up sign
li{ list-style-type: "\\1F44D"; /* thumbs up sign */ }
<ul> <li>Item 1</li> <li>Item 2</li> <li></li> <li>Item 4</li> </ul>
https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type
是的,它的 CSS
要更改項目符號的顏色,請使用 CSS“內容”:
li { list-style: none; position: relative; } li::before { color: #ff2211; /*bullet color*/ content: "\\2022"; /* bullet char */ position:absolute; left:-1.2em; /* indent of the bullet to the text */ }
<ul> <li>Item 1</li> <li>Item 2</li> <li></li> <li>Item 4</li> </ul>
在列表的 css 處編輯列表樣式屬性list-style:none
。 並在 li 中添加 cutom 項目。
<li>
<span style = "color :red">
◉ item 1
</span>
</li>
簡短的回答是否定的,您不能以純 JavaScript 的方式操作這樣的列表。 您需要向 HTML 添加一個class
並通過 JS 更改它,或者使用•
使用span
標簽•
您將使用 CSS 進行樣式設置。 有一點小技巧,但請確保調整列表項的margin
,因為這會使其偏離一點,而且項目符號要小一些,所以嗯。 你的電話,但這里有一個看法:
var addRule = function(selector, styles, sheet) {
styles = (function(styles) {
if(typeof styles === 'string') {
return(styles);
}
var clone = '';
for(var p in styles) {
if(styles.hasOwnProperty(p)) {
var val = styles[p];
p = p.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
}
}
return(clone);
}(styles));
sheet = sheet || document.styleSheets[document.styleSheets.length - 1];
if(sheet.insertRule) {
sheet.insertRule(selector + ' {' + styles + '}', sheet.cssRules.length);
} else if(sheet.addRule) {
sheet.addRule(selector, styles);
}
};
var uls = document.querySelectorAll('ul'), ul = null;
for(var i = 0, len = uls.length; i < len; i++) {
ul = uls[i];
ul.style.listStyle = 'none';
}
addRule('li:before', {
'content': '• ',
'color': 'red'
});
使用我在此處找到的addRule
函數,您首先刪除list-style
屬性的所有ul
元素,並使用li:before
偽選擇來模擬項目符號點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.