【问题标题】:How to add CSS class - in JavaScript?如何在 JavaScript 中添加 CSS 类?
【发布时间】:2018-08-06 12:54:04
【问题描述】:

最近遇到这个:

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

【问题讨论】:

标签: javascript css class styles


【解决方案1】:

有两种方法可以修复它。

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

this.classList.add("active");

  1. 使用setAttribute方法

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

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

【讨论】:

  • 非常感谢!这就是线索——完美!
【解决方案2】:

考虑到您想向 id 为“myDIV”的元素添加类。

 var element = document.getElementById("myDIV");
 element.classList.add("mystyle");

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多