在Javacript中检查复选框时需要添加类
我通过创建一个具有黑暗和轻度模式的网站来挑战自己。
检查复选框时,它在标题上添加类“灯”,例如默认模式。
我创建了一个脚本,但是我没有找到解决方案,为什么它不起作用,有人可以朝这个方向帮助我吗?
这是我的代码:
let header = document.getElementsByClassName('header');
let switcher = document.querySelector('#switch');
switcher.addEventListener('click',function(){
if(this.checked){
header.classList.add('light');
}
else{
header.classList.remove('light');
}
})
<div class="header ">
<div class="title-section">
<h1>Social Media Dashboard</h1>
<p>Total Followers: 23,004</p>
</div>
<div class="switchbtn">
<label for="switch" id="switchlabel">Dark Mode</label>
<input type="checkbox" name="switch" id="switch">
</div>
</div>
i'm challenging myself by creating a website that have a dark and light mode.
When the checkbox is checked, it add the class "light" on the header for example, dark is default mode.
I've created a script but i didn't found the solution and why it's not working, can someone help me in this direction?
Here is my code:
let header = document.getElementsByClassName('header');
let switcher = document.querySelector('#switch');
switcher.addEventListener('click',function(){
if(this.checked){
header.classList.add('light');
}
else{
header.classList.remove('light');
}
})
<div class="header ">
<div class="title-section">
<h1>Social Media Dashboard</h1>
<p>Total Followers: 23,004</p>
</div>
<div class="switchbtn">
<label for="switch" id="switchlabel">Dark Mode</label>
<input type="checkbox" name="switch" id="switch">
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几乎,您只是缺少document.getElementsByClassName的索引。这返回一系列匹配项目。因为您只有一个,所以您只能在阵列中获得第一个问题。
因此,您需要更改的只是:
document.getElementsByClassName to document.getElementsByClassName [0]
,您很高兴!
Almost, you were just missing an index for document.getElementsByClassName. This returns an array of matching items. Because you've only got one you can just get the first in the array no problem.
So all you need to change is:
document.getElementsByClassName to document.getElementsByClassName[0]
and you're good to go!
您可以访问集合中输入的标头的HTML,因此请尝试使用
我更喜欢使用 querySelector()添加和删除类,这更简单。
You can access the HTML of the header entering inside the collection, so try using
I prefer using querySelector() for adding and removing classes, it's simpler.
我对代码进行了一些更改,以便您可以拥有基础并开始工作。
我更改了getElementsByClassName为getElementById,因为第一个将返回所有元素的数组,其中此类名称。
另外,当您单击时,我将其变为默认和黑暗。
希望它有帮助。
I made some changes to the code so that you can have a base and start working.
I changed getelementsbyclassname to getElementById since the first one will return an array of all elements with this class name.
Also, I made it white as default and dark when you click.
Hope it helps.