javascript怎么修改类

javascript怎么修改类,第1张

javascript怎么修改类

在JavaScript中,可利用classList属性配合toggle()方法来修改类,classList属性用于返回元素的类名,toggle()方法用于在元素中切换类名,语法为“element.classList.toggle(类名)”。

本教程 *** 作环境:windows10系统、javascript1.8.5版、Dell G3电脑。

javascript怎么修改类

classList 属性返回元素的类名,作为 DOMTokenList 对象。

该属性用于在元素中添加,移除及切换 CSS 类。

classList 属性是只读的,但你可以使用 add() 和 remove() 方法修改它。

语法为:

element.classList

add(class1, class2, ...) 在元素中添加一个或多个类名。

如果指定的类名已存在,则不会添加

contains(class) 返回布尔值,判断指定的类名是否存在。

可能值:

true - 元素包已经包含了该类名

false - 元素中不存在该类名

item(index) 返回元素中索引值对应的类名。索引值从 0 开始。

如果索引值在区间范围外则返回 null

remove(class1, class2, ...) 移除元素中一个或多个类名。

注意: 移除不存在的类名,不会报错。

toggle(class, true|false) 在元素中切换类名。

第一个参数为要在元素中移除的类名,并返回 false。

如果该类名不存在则会在元素中添加类名,并返回 true。

第二个是可选参数,是个布尔值用于设置元素是否强制添加或移除类,不管该类名是否存在。例如:

移除一个 class: element.classList.toggle("classToRemove", false);

添加一个 class: element.classList.toggle("classToAdd", true);

示例如下:

<html>
<head>
<meta charset="utf-8">
<title>123</title>
<style>
.mystyle {
    width: 300px;
    height: 50px;
    background-color: coral;
    color: white;
    font-size: 25px;
}
.newClassName {
    width: 400px;
    height: 100px;
    background-color: lightblue;
    text-align: center;
    font-size: 25px;
    color: navy;
    margin-bottom: 10px;
}
</style>
</head>
<body>
<p>点击按钮切换类名。</p>
<button onclick="myFunction()">点我</button>
<p><strong>注意:</strong> Internet Explorer 9 及更早 IE 版本浏览器不支持 classList 属性。</p>
<div id="myDIV" class="mystyle">
我是一个 DIV 元素。
</div>
<script>
function myFunction() {
    document.getElementById("myDIV").classList.toggle("newClassName");
}
</script>
</body>
</html>

输出结果:

点击按钮后:

相关推荐:javascript学习教程

以上就是javascript怎么修改类的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/699899.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存