gpt4 book ai didi

javascript - 我的 sidenav 颜色没有随着按钮(点击)而改变

转载 作者:行者123 更新时间:2023-11-28 19:25:00 25 4
gpt4 key购买 nike

我创建了一个 JS 脚本,它通过点击一个按钮来改变我的侧边菜单的背景,但它没有改变任何东西

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function toggle_visibility() {
var e = document.getElementById('on');
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';

var f = document.getElementById('off');
if(f.style.display =='block')
f.style.display = 'none';
else
f.style.display = 'block';

var g = document.getElementById('sidenav');
if(g.style.background == '#F5F5F5') {
g.style.background = '#252525';
}
if(g.style.background == '#252525') {
g.style.background = '#F5F5F5';
}
}
</script>
</head>
<body id='body'>
<div id="sidenav" style="background: #F5F5F5">
<div class="btn-area" onclick="toggleNav()">&#9776</div>

<ul>

<div class="button">
<button onclick="changeColor(); backgroundHiding(); toggle_visibility();" class="lightbutton">
<span id="on">Turn Off the lights</span>
<span id="off" style="display: none">Turn On the lights</span>
</button>
</div>
</ul>

</div>
</body>
</html>

我希望它将我的背景更改为 id='sidenav' 但它并没有改变任何东西......如果有人帮助我,我将不胜感激乌乌

最佳答案

因此,您可以通过对样式和 JS 进行一些修改来完成此操作。只需使用 g.classList.toggle('lights-on')。创建类也优于内联样式。确保为 sidenav 提供 lights-on 的起始类。

完整代码如下:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function toggle_visibility() {
var e = document.getElementById('on');
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';

var f = document.getElementById('off');
if(f.style.display =='block')
f.style.display = 'none';
else
f.style.display = 'block';

var g = document.getElementById('sidenav');
g.classList.toggle('lights-off'); //<--- here is the toggle instead of your ifs
}

</script>
</head>
<body id='body'>
<div id="sidenav" class="lights-on"> <!-- make sure you add this class -->
<div class="btn-area" onclick="toggleNav()">&#9776</div>

<ul>

<div class="button">
<button onclick="changeColor(); backgroundHiding(); toggle_visibility();" class="lightbutton">
<span id="on">Turn Off the lights</span>
<span id="off" style="display: none">Turn On the lights</span>
</button>
</div>
</ul>

</div>
</body>
</html>

你的样式表应该是这样的:

.lights-on {
background-color: #f5f5f5;
}

.lights-off {
background-color: #252525;
}

作为旁注,我建议为您的方法使用一致的命名,因此 toggle_visibility() 应该是 toggleVisibility()

关于javascript - 我的 sidenav 颜色没有随着按钮(点击)而改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com