JavaScript 如何移除使用.css()函数添加的样式
在内容越来越交互式的许多情况下,开发人员希望根据用户输入、后台运行的某些代码以及其他因素动态应用样式。在这些情况下,涉及样式规则或内联样式的CSS模型无法帮助解决问题。
解决所有这些问题的方法涉及JavaScript/jQuery。它不仅可以让我们为用户交互的元素设置样式,更重要的是,它允许开发人员为页面上的所有元素设置样式。这种自由非常强大,并且远远超出了CSS仅能在其内部样式内容的有限能力。
- JavaScript:
removeAttribute(): 从元素中移除指定名称的属性。
setAttribute(): 在指定的元素上设置属性的值。
示例-1: 以下示例演示如何在JavaScript中设置/移除样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript示例</title>
</head>
<body>
<div>
<p id="gfg">
Welcome to geeks for geeks
</p>
</div>
<button type="button"
id="setstyle"
onclick="setstyle()">
Set Style
</button>
<button type="button"
id="removestyle"
onclick="removestyle()"
disabled>
Remove Style
</button>
</body>
<script type="text/javascript">
removestyle = () => {
document.getElementById(
"gfg").removeAttribute("style");
document.getElementById(
"setstyle").removeAttribute("disabled");
document.getElementById(
"removestyle").setAttribute("disabled", "true");
};
</script>
</html>
输出:
在样式之前:

点击设置样式后:

点击移除样式后:

示例-2: 下面的示例演示了如何在jQuery中设置/删除样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery示例</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity=
"sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
</head>
<body>
<div>
<p id="gfg">
欢迎来到geeks for geeks
</p>
</div>
<button type="button"
id="setstyle"
onclick="setstyle()">
设置样式
</button>
<button type="button"
id="removestyle"
onclick="removestyle()"
disabled>
删除样式
</button>
</body>
<script type="text/javascript">
(document).ready(() => {
setstyle = () => {("#gfg").css({
"color": "white",
"background-color": "green",
"padding": "10px",
});
("#setstyle").attr("disabled", "true");("#removestyle").removeAttr("disabled");
}
});
</script>
</html>
输出:
在样式化之前:

点击设置样式之后:

点击删除样式之后:

极客教程