我有一个CSS中的自定义开关,我在django的模板中使用。我正确加载了javascript文件,但当我使用开关时,我没有得到预期的结果。预期的结果是背景会改变颜色,但使用开关时却无法实现。我在模板中添加了一个按钮,看看这个按钮是否能正常工作,结果确实如此。
javascript文件。
function darkModen() {
var element = document.body;
element.classList.toggle("dark-mode");
}
HTML开关,这个什么都不做。
<div class="onoffswitch" style="position: fixed;left: 90%;top: 4%;" onclick="darkMode()">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="darkMode">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
HTML按钮,做了预期的事情。
<button onclick="darkMode()">Toggle dark mode</button>
如果是这个问题导致的,请CCS。
.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #000000; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 16px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 5px;
background-color: #FAFAFA; color: #A87DFF;
darkMode()
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 5px;
background-color: #FAFAFA; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #2E2E2E;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #000000; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
background-color: #27A1CA;
}
body {
color: black;
}
.dark-mode {
background-color: rgb(66, 66, 66);
color: white;
}
我一直在尝试了解按钮是如何工作的,而开关却不工作。这是否因为我不能在浏览器中使用onclick而发生。div
标签?我也想知道,如果django有特殊的方法来使用javascript,是否会造成这种情况。我可以看到javascript文件已经被加载到网站中,因为我可以得到。http:/127.0.0.1:8000staticlighting.js。 并在这里看到这个脚本。
解决方案:
我建议你创建一个事件处理程序来处理 checkbox
并听取 change
事件,以确定是否对其进行了检查,从而确保您正确应用了 dark-mode
阶级到 body
标签。
这里有一个可能的解决方案。
var body = document.body;
var checkbox = document.querySelector("#onoffswitch");
checkbox.addEventListener("change", function(event) {
var target = event.target;
var isChecked = target.checked;
if (isChecked) {
body.classList.add("dark-mode");
} else {
body.classList.remove("dark-mode");
}
});
.dark-mode {
background-color: grey;
color: white;
}
<div>
<label for="onoffswitch">
<span>Toggle dark mode on or off.</span>
</label>
<input type="checkbox" name="onoffswitch" id="onoffswitch" />
</div>
暂无讨论,说说你的看法吧