getElementByID逻辑在IF语句中不起作用,但作为函数起作用。

huangapple go评论67阅读模式
英文:

(JS) getElementByID logic doesn't work in IF statement, but works as a function

问题

尝试设置一个简单的持续存在的深色模式功能。深色模式本身可以工作,但不能隐藏按钮显示(它们只会在点击后隐藏,触发函数后才会隐藏)。

编辑:我应该澄清一下 - 我遇到的问题是让按钮在刷新页面或点击到不同页面时保持隐藏。深色模式仍然存在(黑色背景和白色文本),但按钮会重新显示,直到我再次点击它。

在控制台中,我收到以下错误 - 无法读取 null 的属性(读取 'style')
在 js:27:36 处

抱歉,我是 JavaScript 新手。

var body = document.querySelector("body");

var theme = localStorage.getItem('darkmode');

function dark() {
  body.style.color = 'white';
  body.style.backgroundColor = 'black';
  document.getElementById('dark').style.display = 'none';
  document.getElementById('light').style.display = 'block';
  localStorage.setItem('darkmode', true);
}

function light() {
  body.style.color = 'black';
  body.style.backgroundColor = 'white';
  document.getElementById('light').style.display = 'none';
  document.getElementById('dark').style.display = 'block';
  localStorage.setItem('darkmode', false);
}

if (theme == "true") {
  body.style.color = 'white';
  body.style.backgroundColor = 'black';
  document.getElementById('dark').style.display = 'none';
  document.getElementById('light').style.display = 'block';
} else if (theme == "false") {
  body.style.color = 'black';
  body.style.backgroundColor = 'white';
  document.getElementById('light').style.display = 'none';
  document.getElementById('dark').style.display = 'block';
}
<a id='dark' class='navbar-link' href="#" onclick="dark()" role="button">Darkmode!</a>
<a id='light' class='navbar-link' href="#" onclick="light()" role="button">Lightmode!</a>

似乎是一个 getElementByID 的问题,因为 if 函数的其余部分按预期工作,不确定是否必须通过函数调用触发此问题,或者是否有其他替代方法。

英文:

Attempting to set up a simple dark mode function that persists. The dark mode itself works, but can't hide button display (they will only hide once clicked on and the function is triggered).

Edit: I should clarify - the issue I am having is getting the button to stay hidden on refresh/when I click to a different page. The dark mode remains (black background & white text) but the button reappears until I click it again.

In my console I am getting the following error - Uncaught TypeError: Cannot read properties of null (reading 'style')
at js:27:36

Apologies I am new to JavaScript

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var body = document.querySelector(&quot;body&quot;);

var theme = localStorage.getItem(&#39;darkmode&#39;);


function dark() {
  body.style.color = &#39;white&#39;;
  body.style.backgroundColor = &#39;black&#39;;
  document.getElementById(&#39;dark&#39;).style.display = &#39;none&#39;;
  document.getElementById(&#39;light&#39;).style.display = &#39;block&#39;;
  localStorage.setItem(&#39;darkmode&#39;, true);
}

function light() {
  body.style.color = &#39;black&#39;;
  body.style.backgroundColor = &#39;white&#39;
  document.getElementById(&#39;light&#39;).style.display = &#39;none&#39;;
  document.getElementById(&#39;dark&#39;).style.display = &#39;block&#39;;
  localStorage.setItem(&#39;darkmode&#39;, false);
}

if (theme == &quot;true&quot;) {
  body.style.color = &#39;white&#39;;
  body.style.backgroundColor = &#39;black&#39;;
  document.getElementById(&#39;dark&#39;).style.display = &#39;none&#39;;
  document.getElementById(&#39;light&#39;).style.display = &#39;block&#39;;
} else if (theme == &quot;false&quot;) {
  body.style.color = &#39;black&#39;;
  body.style.backgroundColor = &#39;white&#39;
  document.getElementById(&#39;light&#39;).style.display = &#39;none&#39;;
  document.getElementById(&#39;dark&#39;).style.display = &#39;block&#39;;
}

<!-- language: lang-html -->

&lt;a id=&#39;dark&#39; class=&#39;navbar-link&#39; href=&quot;#&quot; onclick=&quot;dark()&quot; role=&quot;button&quot;&gt;Darkmode!&lt;/a&gt;
&lt;a id=&#39;light&#39; class=&#39;navbar-link&#39; href=&quot;#&quot; onclick=&quot;light()&quot; role=&quot;button&quot;&gt;Lightmode!&lt;/a&gt;

<!-- end snippet -->

Seems to be a getElementByID issue as the rest of the if function works as expected, not sure if this has to be triggered by a function call or if there is an alternative.

答案1

得分: 1

问题是theme在按钮被点击之前没有值。当代码第一次运行时,darkmode未在本地存储中设置,因此它将是undefined,这与'true'或'false'不相等。

快速修复是更改您想要作为默认条件的任何值

if (theme === 'true' || theme === undefined) {
// 显示浅色模式
}

或者

if (theme === 'false' || theme === undefined) {
// 显示深色模式
}

但我建议将值theme设置在本地存储中,以在默认情况下删除它

var theme = localStorage.getItem('theme');
function Dark() {
...
localStorage.setItem('theme', 'darkmode');
}
function Light() {
localStorage.removeItem('theme')
}

if (theme === 'darkmode') {
// 显示深色模式
} else {
 // 显示浅色模式
}
英文:

The issue is that theme has no value until a button is clicked. When the code runs for the first time darkmode is not set in local storage and therefore it will be undefined, which is not equal to &#39;true&#39; or &#39;false&#39;.

The quick fix is to change whichever value you want to be the default's conditional

if (theme === &#39;true&#39; || theme === undefined)` {
// show light mode
}

OR

if (theme === &#39;false&#39; || theme === undefined&#39;) {
// show dark mode
}

My suggestion though is to instead set the value theme in local storage "dark mode" to delete it when in default

var theme = localStorage.getItem(&#39;theme&#39;);
function Dark() {
...
localStorage.setItem(&#39;theme&#39;,&#39;darkmode&#39;);
}
function Light() {
localStorage.removeItem(&#39;theme&#39;)
}

if (theme === &#39;darkmode&#39;) {
// show dark
} else {
 // show light
}

</details>



# 答案2
**得分**: 0

您遇到的问题是在加载时主题为空,如果未设置主题。

对于我的回答,我简化了您的代码,将一个dark类切换到body并使用一个单一的链接来切换主题。

body的默认主题设置为浅色主题。我检查darkMode是否存在,如果不存在,将darkMode变量设置为false,表示它处于浅色模式。

如果是darkMode,则向body添加dark类。如果不是暗模式,则不需要执行任何操作。

然后,我附加了一个点击处理程序到您的链接,以便在点击时告诉它要执行什么操作。通过切换dark类,它将要么添加它,要么删除它。

我还将darkMode设置为body是否包含darkMode类(true/false)。

```html
<a class='navbar-link btn-ToggleTheme' href="#" role="button">Change Theme</a>

body{
  color:#000;
  background:#fff;
}

body.dark{
  color:#fff;
  background:#000;
}

const toggleBTN = document.querySelector(".btn-ToggleTheme")
const body = document.body;

const darkMode = localStorage.getItem("darkMode") || false;
if (darkMode) body.classList.add("dark")

toggleBTN.addEventListener("click", (e) => {
    body.classList.toggle("dark");
    localStorage.setItem('darkMode', (body.classList.contains("dark-mode")));
});
英文:

The problem that you are experiencing is theme is empty on load if it wasn't set.

For my answer I simplified your code to toggle a dark class on body and use a single link that toggles the theme.

The body's default theme is set as the light theme. I check to see if darkMode exists and if not, set darkMode variable to false to indicate it's in light mode.

If it is darkMode add the dark class to body. If not dark mode, we don't need to do anything.

Then I attach a click handler to your link so we can tell it what to do on click. By toggling the dark class, it will either add it or remove it.

I also set the darkMode to if body contains the darkMode class or not (true/false).

&lt;a class=&#39;navbar-link btn-ToggleTheme&#39; href=&quot;#&quot; role=&quot;button&quot;&gt;Change Theme&lt;/a&gt;

body{
  color:#000;
  background:#fff;
}

body.dark{
  color:#fff;
  background:#000;
}

const toggleBTN = document.querySelector(&quot;.btn-ToggleTheme&quot;)
const body = document.body;

const darkMode = localStorage.getItem(&quot;darkMode&quot;) || false;
if(darkMode)body.classList.add(&quot;dark&quot;)

toggleBTN.addEventListener(&quot;click&quot;,(e) =&gt; {
    body.classList.toggle(&quot;dark&quot;);
    localStorage.setItem(&#39;darkMode&#39;,(body.classList.contains(&quot;dark-mode&quot;)));
});

huangapple
  • 本文由 发表于 2023年6月22日 01:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定