【发布时间】:2022-01-15 15:19:44
【问题描述】:
我正在尝试根据数据库中给出的值显示代码的 CSS 部分的 ON 和 OFF。我想知道的是如何编辑下面的 CSS 内容(.switch-button:before)以将其更改为 ON 或 OFF。
我尝试为每个元素指定一个 ID 并为其使用 document.getElementById,但它仍然不起作用。
圆圈部分是我要根据数据库值更改的部分。目前,它的默认值(CSS 中的内容)设置为“OFF”。
CSS
.switch-button:before {
content: "OFF";
color: #ffffff;
position: absolute;
top: 0;
bottom: 0;
right: 0;
width: 60px;
display: flex;
align-items: center;
justify-content: center;
z-index: 3;
pointer-events: none;
}
HTML
<div id="turned_onclass" class="turned_onclass" style="display: none;">
<center><label><u>On/Off</u></label></center>
<div class="switch-button">
<input class="switch-button-checkbox" type="checkbox"></input>
<label class="switch-button-label" for=""> <span id="turned_onspan" value="<%= devices.turned_on %>" class="switch-button-label-span">ON</span> </label>
</div>
</div>
Javascript
<script>
/* Button Displays ON/OFF depending on Value */
var turned_onTypeDocument = document.getElementById("turned_onspan");
var turned_onType = turned_onTypeDocument.getAttribute("value");
if (turned_onType == 1) {
document.getElementById("turned_onspan").innerHTML = "ON";
document.getElementById("turned_onspan").style.content = "OFF";
}
if (turned_onType == 0) {
document.getElementById("turned_onspan").innerHTML = "OFF";
var turned_onClassContent = document.getElementsByClassName("switch-button-label-span");
turned_onClassContent.style.content = "ON";
}
///////////////////////////////////////////////
</script>
【问题讨论】:
-
那是因为 JS 不像你期望的那样“反应”。如果您希望复选框触发状态更改,则需要监听其中的事件。例如,如果您的情况,您将需要在复选框上监听
input事件,然后根据元素的值切换开/关状态。 -
你可以做的是使用JS来切换一个类,并让那个类代表开/关样式
标签: javascript html css