首页 > web前端 > js教程 > 正文

如何使用 JavaScript 更改元素的类?

PHPz
发布: 2023-08-30 14:29:04
转载
1497人浏览过

如何使用 javascript 更改元素的类?

className 属性用于更改元素的类。在这里,我们将看到两个例子 -

  • 如何使用 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() 实现了上述目标 -

图改改
图改改

在线修改图片文字

图改改 455
查看详情 图改改

立即学习Java免费学习笔记(深入)”;

<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 更改元素的类?的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号