单击时,我想更改“样式”头中的内部样式表。 (我不想以内联样式对其进行更改!!)我设法将新的divone css添加为文本,但无法删除旧的divone(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;}";
}
最佳答案
function myFunctionTest() {
document.getElementById("style").remove();
var css = '#divone{width: 400px; height: 35px; background-color: red;}',
head = document.head || document.getElementsById('head')[0],
style = document.createElement('style');
head.appendChild(style);
style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}