javascript - 如何在点击时更改头部样式?
问题描述
单击时,我想更改“样式”头中的内部样式表。(我不想以内联样式更改它!!)我设法将新的 divone css 添加为文本,但我无法删除旧的(element.classList.remove ("# divone");)。有没有 idlist.remove?...,或任何其他方式来实现这一点。有什么想法或建议吗?谢谢你
<!DOCTYPE html>
<html>
<head>
<style id="style">
#divone{
width: 500px;
height: 50px;
background-color: red;
}
#divtwo{
width: 400px;
height: 80px;
background-color: purple;
}
</style>
</head>
<div id="divone"></div>
<div id="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>
function myFunctionTest() {
var element = document.getElementById("style");
element.classList.remove("#divone");
document.getElementById("style").textContent += "#divone{width: 400px; height: 35px; background-color: red;}";
}
解决方案
您尝试删除类但使用id
如下所示。将 id 符号更改#
为类符号,.
同时将 DOM id 更改为类名:
function myFunctionTest() {
var element = document.getElementById("style");
element.classList.remove("divone");
document.getElementById("style").textContent += ".divone{width: 400px; height: 35px; background-color: blue;}";
}
<!DOCTYPE html>
<html>
<head>
<style id="style">
.divone{
width: 500px;
height: 50px;
background-color: red;
}
</style>
</head>
<div class="divone">hello !!</div>
<div class="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>
正如您的评论一样,请使用ID
function myFunctionTest() {
var element = document.querySelectorAll("#style")[0].sheet;
for (var i = 0; i < element.cssRules.length; i++) {
if (element.cssRules[i].selectorText === '#divone') {
element.deleteRule(i);
}
}
document.getElementById("style").textContent += "#divone{width: 400px; height: 35px; background-color: blue;}";
}
<!DOCTYPE html>
<html>
<head>
<style id="style">
#divone {
width: 500px;
height: 50px;
background-color: red;
}
</style>
</head>
<div id="divone">hello !!</div>
<div id="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>