交替颜色 onClick

alternate colors onClick

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

当我按下按钮时,它会改变颜色,但当我按下第二次时,它不会变回原来的颜色。我该如何解决这个问题?

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

具体结账 .toggle()。这是一个本地解决方案。不需要 Deps,处理周围的逻辑要简单得多。干杯。

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

据推测,背景颜色可以是 3 个值之一,"cyan"、"lavenderblush"、任何其他值

现在,如果逻辑是

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";
}

这是第一个 "logic" 作为可运行的片段

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>