代码之家  ›  专栏  ›  技术社区  ›  Wolk

交替颜色onClick

  •  0
  • Wolk  · 技术社区  · 7 年前

    我正在开发一个javascript函数,每次按下按钮时,该函数将使div元素的背景色在淡紫色和青色之间交替。

    当我按下一次按钮时,它会改变颜色,但第二次按下时不会变回原来的颜色。如何修复此问题?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Jaromanda X    7 年前

    据推测,背景颜色可以是3个值之一,“青色”、“薰衣草色”, 还有别的吗

    现在,如果逻辑是

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  lavenderblush
    

    那么代码应该是

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "lavenderblush") {
        style.backgroundColor = "cyan";
    } else {
        style.backgroundColor = "lavenderblush";
    }
    

    或者,如果逻辑是

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  cyan
    

    那么代码是

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "cyan") {
        style.backgroundColor = "lavenderblush";
    } else {
        style.backgroundColor = "cyan";
    }
    

    但是,如果逻辑是

    Current          Changes to
    --------------   -------------
    cyan             lavenderblush
    lavenderblush    cyan
    *anything else*  *do not change*
    

    那么代码是

    var style = document.getElementById('new').style;
    if (style.backgroundColor === "cyan") {
        style.backgroundColor = "lavenderblush";
    } else if (style.backgroundColor === "lavenderblush") {
        style.backgroundColor = "cyan";
    }
    

    这是第一个作为可运行代码段的“逻辑”

    function Replace() {
        var style = document.getElementById('new').style;
        if (style.backgroundColor === "lavenderblush") {
            style.backgroundColor = "cyan";
        } else {
            style.backgroundColor = "lavenderblush";
        }
    }
    document.getElementById('Replace').addEventListener('click', Replace);
    <button id="Replace">Click</button>
    <div id="new">NEW</div>
        2
  •  0
  •   DaneTheory    7 年前

    让您的生活更轻松,使用 classList API 以编程方式处理样式更改。

    特别是签出 .toggle() .这是本机解决方案。不需要DEP,只需处理更简单的逻辑即可。干杯

    https://developer.mozilla.org/en-US/docs/Web/API/Element/classList