【问题标题】:How to Change CSS Content using IF Statement in Javascript如何在 Javascript 中使用 IF 语句更改 CSS 内容
【发布时间】:2022-01-15 15:19:44
【问题描述】:

我正在尝试根据数据库中给出的值显示代码的 CSS 部分的 ON 和 OFF。我想知道的是如何编辑下面的 CSS 内容(.switch-button:before)以将其更改为 ON 或 OFF。

我尝试为每个元素指定一个 ID 并为其使用 document.getElementById,但它仍然不起作用。

圆圈部分是我要根据数据库值更改的部分。目前,它的默认值(CSS 中的内容)设置为“OFF”。

Output

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


【解决方案1】:

虽然可能动态更改 CSS,但更好的方法是正确设置初始规则。例如,您可以切换一个类以生成新的:before 内容。

.switch-button:before {
    content: "OFF";
    color: #ffffff;
    ....
}
.switch-button.on:before {
    content: "ON";
}

然后就做

for (const input of document.querySelectorAll('.switch-button-checkbox')) {
  input.addEventListener('change', (e) => {
    input.parentElement.classList.toggle('on', e.checked);
  });
}

for (const input of document.querySelectorAll('.switch-button-checkbox')) {
  input.addEventListener('change', (e) => {
    input.parentElement.classList.toggle('on', e.checked);
  });
}
.switch-button:before {
  content: "OFF";
}

.switch-button.on:before {
  content: "ON";
}
<div class="switch-button">
  <input class="switch-button-checkbox" type="checkbox">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多