【问题标题】:Add a button to change to dark mode in react website在反应网站中添加一个按钮以更改为暗模式
【发布时间】:2021-11-02 15:04:48
【问题描述】:

我想在我的网站上调出一个按钮,让用户可以随时更改为深色或浅色模式。我按照教程进行了暗模式,但问题是用户必须按 Enter 键才能进入暗模式。但我希望有一个按钮可以帮助他们更改为暗模式或亮模式这是我的代码在js中使用:-

<script>
      window.onload = function () {
  document.onkeypress = function (e) {
    console.log(e);
    e = e || window.event;
    if (e.keyCode === 13) {
      document.documentElement.classList.toggle("dark-mode");
      document.querySelectorAll(".inverted").forEach((result) => {
        result.classList.toggle("invert");
      });
    }
  };
};
    </script>

这是我在 css 中使用的:-

.dark-mode {
  filter: invert(1) hue-rotate(180deg);
}
.invert {
  filter: invert(1) hue-rotate(180deg);
}'

js 中的 .inverted 类是因为我不希望图像反转它们的颜色.. 所以我给所有图像一个 class='inverted'

所以,这就是我所做的,有人请让我知道我应该如何调出一个更改为深色或浅色模式的按钮,而不是按 Enter 键

谢谢!

【问题讨论】:

  • 你在react.js工作吗?你的问题是纯javascript
  • 实际在index.html文件和app.js中的其他东西中使用了这个

标签: javascript html css reactjs


【解决方案1】:

您可以在按钮上的onClick 事件上运行该函数,如下所示:

<button onClick="toggleMode()">Toggle Mode</button>

<script>
  function toggleMode () {
      document.documentElement.classList.toggle("dark-mode");
      document.querySelectorAll(".inverted").forEach((result) => {
        result.classList.toggle("invert");
      })
  }
</script>

【讨论】:

    【解决方案2】:

    您可以在 HTML 页面上创建一个按钮,然后为其附加一个事件侦听器。

    function myfunction(e) {
      console.log("you clicked");
      document.documentElement.classList.toggle("dark-mode");
      document.querySelectorAll(".inverted").forEach((result) => {
        result.classList.toggle("invert");
      });
    }
    const btn = document.querySelector('.btn')
    btn.addEventListener('click', myfunction);
    &lt;button class="btn"&gt;Dark Mode&lt;/button&gt;

    顺便说一句,你为什么在 react-app 中使用 script 标签?

    【讨论】:

    • 没有在app.js中使用。。就像我在index.html中使用的一样
    • 顺便说一句,成功了!谢谢!:)
    • 如果您能对此投赞成票会很有帮助。谢谢?
    • 这样做了,但显示需要 15 个声望,抱歉呵呵
    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2016-02-21
    相关资源
    最近更新 更多