最近我遇到了这个:
如果我在 JS:22 行中添加 this.classlist.add("active");
那么它应该根据 CSS 类更改颜色, 但是这是行不通的。任何想法?
var newItem = 1;
var ourList = document.getElementById("test_id");
var ourButton = document.getElementById("Button_id");
var test_function = document.getElementById("Headline");
var OurListID = document.getElementById("test_id").getElementsByTagName('li')
for (i = 0; i < OurListID.length; i++) {
OurListID[i].addEventListener("click", activateItem );
}
function activateItem () {
test_function.innerHTML = this.innerHTML;
this.classlist.add("active");
}
ourButton.addEventListener("click", NewFunctionName );
function NewFunctionName () {
test_id.innerHTML += "<li>Something New " + newItem + "</li>";
newItem++;
}
/** JavaScriptGenius: 19 min 23 sec - continue **/
.active {
background-color: blue;
}
<!Doctype html>
<html>
<head>
<title>Take me to the paradise city</title>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<h1 id="Headline">Test Headline</h1>
<p id="IDTest">Click a list item to replace this text.</p>
<button id="Button_id">Add new item</button>
<div>
<ul id="test_id">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
</ul>
</div>
<div>
<p>JavaScript Test page</p>
</div>
<script src="JavaScriptGenius.js"></script>
</body>
</html>
最佳答案
有两种方法可以修复它。
- 使用 classList 属性:IE9 及更早版本不支持 classList 属性。
this.classList.add("active");
- 使用setAttribute方法
this.setAttribute('class','active');
或
this.setAttribute('class',this.getAttribute('class')+' active');
关于javascript - 如何在 JavaScript 中添加 CSS 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708153/