如何在仅使用Javascript / HTML单击按钮时更改按钮的文本和颜色

时间:2016-12-06 03:58:12

标签: javascript

我需要能够将按钮颜色和文本更改为默认值以外的其他颜色。

<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 个答案:

答案 0 :(得分:1)

您的代码段在定义变量和文本方面存在一些问题。 PartyBtn更新为-1和“派对时间!”作为小时数和“Party Over”,我认为不应该是一个接一个。

使用一些格式和变量声明更新了代码段。希望这能让你前进。

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>