【问题标题】:How to remove style from <html>如何从 <html> 中删除样式
【发布时间】:2021-08-19 14:33:05
【问题描述】:

我想从 html 中移除 style 属性:style="">

例如:

<html style="--athens-gray:#121212; --alabaster:#1E1E1E; --black:#ffffff; --white:#000000;">

应该是&lt;html&gt;

这是我的脚本:

const themes = {
  dark: {
      '--white': '#000000',
  },
  light: {
      '--white': '#ffffff',
  },
};
function lighttheme() {
const theme = themes["dark"];
    for (var variable in theme) {
            document.documentElement.style.setProperty(variable, theme[variable]);
    };
}
:root {
  --athens-gray: #e9e8ec;
  --alabaster: #f8f8f8;
  --black: #000000;
  --white: #ffffff;
}

body {
background-color: var(--white);
}
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Settings</title>
    </head>
<body>
<button type="button" onClick="lighttheme();">Click Me!</button>
</body>
</html>

【问题讨论】:

  • 删除是什么意思?
  • 你可以去掉for循环,这样样式属性就不会被设置,样式属性也不会被添加。
  • 我想更改主题,但是当我更改 更改为

标签: html css styles


【解决方案1】:

您可以通过以下代码做到这一点:

document.getElementsByTagName("html")[0].removeAttribute("style")

例如:

const themes = {
  dark: {
      '--athens-gray': '#121212',
      '--alabaster': '#1E1E1E',
      '--black': '#ffffff',
      '--white': '#000000',
  },
  light: {
      '--athens-gray': '#e9e8ec',
      '--alabaster': '#f8f8f8',
      '--black': '#000000',
      '--white': '#ffffff',
  },
};
function lighttheme() {
const theme = themes["dark"];
    for (var variable in theme) {
            document.documentElement.style.setProperty(variable, theme[variable]);
    };
}

function removeStyle(){
    document.getElementsByTagName("html")[0].removeAttribute("style");
}
:root {
  --athens-gray: #e9e8ec;
  --alabaster: #f8f8f8;
  --black: #000000;
  --white: #ffffff;
}

body {
background-color: var(--white);
}
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Settings</title>
    </head>
<body>
<button type="button" onClick="lighttheme();">Click Me!</button>
<button type="button" onClick="removeStyle()">Remove Style!</button>
</body>
</html>

如果我评论 javascript 代码,您会看到页面颜色变红。

【讨论】:

  • 当我添加此代码时,主题不会改变。
  • 你在调用lighttheme函数吗?
  • 当然,主题改变了,但是 变成了
  • 我编辑你的代码,看看我的答案的变化
  • 我不需要那个。我需要更改颜色但不打印以保持相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多