如何仅使用 Javascript/HTML 单击按钮时更改按钮的文本和颜色
2016-12-06
46
我需要能够将按钮颜色和文本更改为默认颜色和文本以外的其他颜色。
<button id="partyTimeButton">Party Time!</button>
JS
var partyEvent = function()
{
if (partyBtn < 0)
{
partyBtn = new Date().getHours();
partyBtn = "Party Over";
// text in the button should read "Party Over"
// color of the button should be "#0A8DAB" (bonus!)
}
else
{
partyBtn = -1;
partyBtn = "PARTY TIME!";
// text in the button should read "PARTY TIME!"
// color of the button should be "#222" (bonus!)
}
};
partyBtn.addEventListener("click", partyEvent);
1个回答
您的代码片段在定义变量和文本的方式上存在一些问题。 PartyBtn 被更新为 -1 和“派对时间!”以及小时数和“派对结束”,一个接一个,我认为不应该这样。
使用一些格式和变量声明更新了代码片段。希望这能让您开始。
var partyBtn = document.querySelector("#partyTimeButton");
var partyBtnCount = -1;
var partyEvent = function() {
console.log(partyBtnCount);
if (partyBtnCount < 0) {
partyBtnCount = new Date().getHours();
partyBtn.innerHTML = "Party Over";
partyBtn.style.color = "#0A8DAB"
// text in the button should read "Party Over"
// color of the button should be "#0A8DAB" (bonus!)
} else {
partyBtnCount = -1;
partyBtn.innerHTML = "PARTY TIME!";
partyBtn.style.color = ""
// text in the button should read "PARTY TIME!"
// color of the button should be "#222" (bonus!)
}
};
partyBtn.addEventListener("click", partyEvent);
<button id="partyTimeButton">Party Time!</button>
Sreekanth
2016-12-06