javascript - 如何在 JavaScript 中添加 CSS 类?

标签 javascript css class styles

最近我遇到了这个:

如果我在 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>

最佳答案

有两种方法可以修复它。

  1. 使用 classList 属性:IE9 及更早版本不支持 classList 属性。

this.classList.add("active");

  1. 使用setAttribute方法

this.setAttribute('class','active');

this.setAttribute('class',this.getAttribute('class')+' active');

关于javascript - 如何在 JavaScript 中添加 CSS 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51708153/

相关文章:

css - 如何在 react-d3-tree 上定义单独的链接样式

javascript - 将元素扩展到 OS X 上的滚动区域

javascript - 'ng new my-app' 错误

javascript - 使用 Javascript 的背景颜色自动循环

javascript - 在 react 中未定义“可视化” no-undef

javascript - 将子模块注入(inject)主模块

html - 在单个页面上更改菜单样式?

.NET - 如何从对象集合中找到最高公共(public)基类

JAVA - 在启动时运行外部 jar 文件

C++错误: no match for 'operator<<' (operand types are