我有以下列表:
<ul id="objects-list">
<li>Table</li>
<li>Chair</li>
<li>Window</li>
</ul>
使用以下 CSS(取自 https://www.w3schools.com/howto/howto_css_bullet_color.asp ):
ul {
list-style: none;
}
ul li::before {
content: "\2022";
color: red;
font-weight: bold;
display: inline-block;
width: 1em;
}
这会将默认列表标记更改为红色。 一切工作正常,但是当我使用 Javascript 将新元素添加到列表时
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );
它发生在我的 XHTML 文件中。它不会发生在堆栈片段中。
该元素已正确添加到列表中,但根本没有标记。此外,当我在检查器中检查新元素时,它根本不显示“::before”元素。
有人可以解释一下为什么吗?
最佳答案
我已成功使用 XHTML 复制您的问题文件。
问题是 XHTML 区分大小写,li
!= LI
。更改添加元素的代码以使用 li
:
var listItem = document.createElement("li");
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^
这是演示该问题的完整 XHTML 文件。如果您想在本地验证它,请确保使用正确的 Content-Type
提供文件(使用扩展名 .xhtml
并从文件系统打开它也可以,至少在 Chrome 及其变体中):
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML CSS Problem</title>
<style>
ul {
list-style: none;
}
ul li::before {
content: "\2022";
color: red;
font-weight: bold;
display: inline-block;
width: 1em;
}
</style>
</head>
<body>
<ul id="objects-list">
<li>Table</li>
<li>Chair</li>
<li>Window</li>
</ul>
<script>
var objectsList = document.getElementById("objects-list");
var listItem = document.createElement("LI");
listItem.innerHTML = "Pen";
objectsList.appendChild(listItem );
</script>
</body>
</html>
关于javascript - 动态添加元素时,为什么::before CSS 选择器不适用于列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60204837/