[英]How to change text and color of a button when it is clicked using Javascript/HTML only
I need to be able to change the a button color and text to something other than the default. 我需要能够将按钮的颜色和文本更改为默认以外的其他颜色。
<button id="partyTimeButton">Party Time!</button>
JS 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);
Your code snippet has some issues with the way you defined variables and text. 您的代码段在定义变量和文本的方式上存在一些问题。 PartyBtn is updated as -1 and "Party time!" PartyBtn更新为-1和“ Party time!”。 and as hours number and "Party Over" , one after the other, which I think, shouldn't be. 作为小时数和“ Party Over”,我认为不应该一个接一个。
Updated the snippet with some formatting and variables declarations. 使用一些格式和变量声明更新了代码段。 Hope this should get you going. 希望这可以帮助您前进。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.