如何使用 classname 属性更改元素的类。如何在新旧课程之间切换。使用 classname 属性更改元素的类在此示例中,我们将使用 classname 属性更改元素的类。假设我们有一个带有 oldstyle 类的 div -
<div id=mydiv class=oldstyle> <p>the div...</p></div>
我们将使用 classname 属性将上面的 oldstyle 类设置为一个新类,即 newstyle -
function demofunction() { document.getelementbyid(mydiv).classname = newstyle;}
我们通过单击以下按钮调用 demofunction() 实现了上述目标 -
<p>click the below button to change the class</p><button onclick=demofunction()>change class</button>
示例让我们看看完整的例子 -
<!doctype html><html><style> .oldstyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newstyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; }</style><body> <h1>changing the class</h1> <p>click the below button to change the class</p> <button onclick=demofunction()>change class</button> <div id=mydiv class=oldstyle> <p>the div...</p> </div> <script> function demofunction() { document.getelementbyid(mydiv).classname = newstyle; } </script></body></html>
在新旧类之间切换示例我们还可以创建一个适用于两种方式的按钮,即切换。再次单击按钮会将其切换回来 -
<!doctype html><html><style> .oldstyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newstyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; }</style><body> <h1>toggle the class</h1> <p>click the below button to toggle the classes</p> <button onclick=demofunction()>toggle class</button> <div id=mydiv class=oldstyle> <p>the div...</p> </div> <script> function demofunction() { const element = document.getelementbyid(mydiv); if (element.classname == oldstyle) { element.classname = newstyle; } else { element.classname = oldstyle; } } </script></body></html>
以上就是如何使用 javascript 更改元素的类?的详细内容。
