按钮应从原始(黑色)切换为黄色,然后还原。我的问题是将其还原。在if-else语句中,只有else语句起作用。我已经尝试过switch语句,但这不起作用 html
var buttonElement = document.getElementById("title-button");
var elementbutton = buttonElement;
var elementsArray = document.getElementsByTagName("h1");
var element = elementsArray[0];
elementbutton.addEventListener( "click", function(){
if(elementbutton.hasOwnProperty("yellow")){
element.remove("yellow");
element.classList.remove("bordered-text");
element.style.add = "black";
} else {
element.style.color = "yellow";
element.classList.add("bordered-text");
}
});
.bordered-text{
border-style: solid;
border-color: black;
}
<button id="title-button">Alters title</button>
<h1>Header 1</h1>
答案 0 :(得分:0)
您所单击的按钮没有名为 yellow 的任何属性,因此elementbutton.hasOwnProperty("yellow")
的计算结果始终为false
,因此 else 块始终在执行。
您应检查hasOwnProperty
中的element.style.color
,而不是检查单击的按钮的h1
:
var buttonElement = document.getElementById("title-button");
var elementbutton = buttonElement;
var elementsArray = document.getElementsByTagName("h1");
var element = elementsArray[0];
elementbutton.addEventListener( "click", function(){
if(element.style.color == "yellow"){
element.style.color = "black";
element.classList.remove("bordered-text");
} else {
element.style.color = "yellow";
element.classList.add("bordered-text");
}
});
.bordered-text{
border-style: solid;
border-color: black;
}
<button id="title-button">Alters title</button>
<h1>Header 1</h1>