2017-12-09 6 views
1

다음 코드를 사용하여 기타 문자열의 색상을 첫 번째 클릭에서 빨간색으로, 두 번째 클릭에서 연한색, 등 뒤로 두 가지 색상. 첫 번째 클릭에서 문자열이 빨간색으로 바뀌지 만 다음 클릭과 함께 빨간색으로 유지되며 그 이유를 알 수 없습니다.(배경색) 스위치가 작동하지 않습니다.

var string = document.getElementById("a-string"); 
if (string.backgroundColor !== "red") { 
    string.style.backgroundColor = "red"; 
} else { 
    string.style.backgroundColor = "lightblue"; 
} 

캠 누구도 내가 예상 한대로 작동하지 않아야하는 이유를 알 수 있습니까?

+5

변경'경우 ('에 string.backgroundColor! == ...이'(string.style.backgroundColor이! == ...' – destoryer

+1

와우, 감사, 미안 내가 멍청한 놈이야 경우 그걸 발견 했어야 했어. – nmh

답변

0

코드에 오류가 거의 없습니다. 오류는 string.backgroundColor !== "red"입니다. 그것은 string.style.backgroundColor !== "red"

var string = document.getElementById("a-string"); 
if (string.style.backgroundColor !== "red") { 
    string.style.backgroundColor = "red"; 
} 
else { 
    string.style.backgroundColor = "lightblue"; 
} 
0

var string = document.getElementById("a-string"); 
 
if (string.style.backgroundColor !== "red") { 
 
    string.style.backgroundColor = "red"; 
 
} else { 
 
    string.style.backgroundColor = "lightblue"; 
 
}
div{ 
 
font-size:30px; 
 
}
<div id="a-string"> A Sample Text</div>

0

classList.toggle()으로 단축해야합니다. 요소에 기본 배경색을 설정합니다. 다른 배경색이 포함 된 클래스로 토글합니다.

var btn = document.querySelector("button"), 
 
    div = document.querySelector("div"); 
 

 
btn.addEventListener("click", function() { 
 
    div.classList.toggle("bg-red"); 
 
});
div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: lightblue; 
 
} 
 

 
.bg-red { 
 
    background: red; 
 
}
<div></div> 
 
<button id="btn">Toggle background color</button>