2016-09-30 3 views
0

버튼을 클릭하여 현재 색상을 기준으로 div의 배경색을 변경하려고합니다.Javascript - 현재 색상을 기준으로 div의 색상을 변경하십시오.

색 시안 인 경우, 예를 들어, (#의 00FFFF이 -가) 옐로우 ('FFFF00 변경한다

를 색이 황색 인 경우 -. 그것은 (마젠타로 변경한다 # FF00FF)

한다. 색상이 마젠타 색이면 - 시안 색으로 되돌려 야합니다.

시안 색에서 노란색으로 색을 바꿀 수 있었지만, if 문을 쓰는 방법을 잘 모르겠습니다 (if 문을 사용하는 것이 가장 좋은 방법이라고 가정). ?) 현재 색을 기준으로 색을 변경합니다.

function ColorFunction() { 
 
    if (light.getItem("backgroundColor") == '#00ffff') { 
 
    document.getElementById("light").style.backgroundColor = "#ffff00"; 
 
    } 
 
    else 
 
    if (light.getItem("backgroundColor") == '#ffff00') { 
 
     document.getElementById("light").style.backgroundColor = "#ff00ff"; 
 
    } 
 
    else 
 
    if (light.getItem("backgroundColor") == '#ff00ff') { 
 
     document.getElementById("light").style.backgroundColor = "00ffff"; 
 
    } 
 
}
.main { 
 
    width:250px; 
 
    color: #202020; 
 
    background-color: #d0d0d0; 
 
} 
 

 
.light { 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: #00ffff 
 
} 
 

 
#burn { 
 
    width: 150px; 
 
    font-style: italic; 
 
} 
 

 
#button { 
 
    font-style: bold; 
 
    width: 150px; 
 
}
<h1>Disco Inferno</h1> 
 
    <div class="light" id="light"> 
 
     div 
 
    </div> 
 

 
    <button onClick="ColorFunction()">Burn!</button>

+1

이 코드 결과는 없습니다.) – Jamiec

+0

console.log()는 실패한 이유를 보여줍니다. 수업을 이용하십시오. – epascarello

+2

@Jamiec So ...그것은 첫 번째 실수가 될 것입니다. –

답변

4

좋아, 여기에 처음부터 시작 할 수 있습니다.

id가 light 인 요소가 있지만 자바 스크립트에서 사용할 수있는 변수가 자동으로 없습니다. 충분히 쉬운 그것을 하나를 만들려면 :

var light = document.getElementById("light"); 

을 그리고, 난 당신이에서 getItem 어디서 모르겠어요 - 아마도 그것은 추측했다 - 그러나 HTMLElement

당신은 수에 미치는 유효한 방법 light.style.backgroundColor와 함께하세요 - 아래 스 니펫을 참조하십시오.

var colors = ["rgb(0, 255, 255)","rgb(255, 255, 0)","rgb(255, 0, 255)"]; 
 

 
function ColorFunction() { 
 
    var light = document.getElementById("light"); 
 
    var curr = light.style.backgroundColor; 
 
    var next = colors.indexOf(curr)+1; 
 
    light.style.backgroundColor = colors[next%colors.length]; 
 
}
<h1>Disco Inferno</h1> 
 
<div class="light" id="light" style="background-color:#00FFFF"> 
 
    Burn, baby burn! 
 
</div> 
 

 
    <button onClick="ColorFunction()">Burn!</button>

+0

* "id light가있는 요소가 있지만 자바 스크립트에서 사용할 수있는 변수가 자동으로되지 않습니다."* 실제로는 . 'id'가있는 요소는 [자동 전역 변수 *가 만들어집니다] (https://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object). –

+0

@ T.J.Crowder sshhhhh입니다. 사람들이 * 사용하는 좋은 생각을 믿게하지 마라. – Jamiec

+0

** : -) ** 실제로 사양에 추가되었으므로 포기했습니다. –

2

는 직접 사업부에 색상을 할당 한 후, 색상을 이동하기위한 객체를 사용할 수 있습니다.

function ColorFunction() { 
 
    var colors = { 
 
      'rgb(0, 255, 255)': 'rgb(255, 255, 0)', 
 
      'rgb(255, 255, 0)': 'rgb(255, 0, 255)', 
 
      'rgb(255, 0, 255)': 'rgb(0, 255, 255)' 
 
     }, 
 
     element = document.getElementById("light"); 
 
    element.style.backgroundColor = colors[element.style.backgroundColor]; 
 
}
.main { width:250px; color: #202020; background-color: #d0d0d0; } 
 
.light { width: 50px; height: 50px; background-color: #00ffff; } 
 
#burn { width: 150px; font-style: italic; } 
 
#button { font-style: bold; width: 150px; }
<div class="light" id="light" style="background-color: #00ffff;"></div> 
 
<button onClick="ColorFunction()">Burn!</button>

2

몇 가지로 구성 방법 더의 getItem()이 없다. 콘솔을 보면 오류라고 볼 수 있습니다. 배경색을 읽으려면 스타일을 사용해야합니다. 당신이 요소의 ID와 일치하는 변수를 정의하고 마술 그렇게 안되는 element.You에 대한 참조입니다

var color = elementReference.style.backgroundColor 

이제 자바 스크립트의 나쁜 기능에 의존하고 있습니다. 직접 변수를 정의해야합니다.

var elementReference = document.getElementById("light"); 

이제 색상 값을 읽을 때 브라우저가 다른 것을 반환합니다. SOme hex, 일부 rgb. 색상을 확인하는 것은 나쁜 일입니다. 무엇을해야합니까? CSS 클래스를 사용하십시오.

function ColorFunction(){ 
 
    var elem = document.getElementById("light"); 
 
    if(elem.classList.contains("red")) { 
 
    elem.classList.remove("red"); 
 
    elem.classList.add("blue"); 
 
    } else if(elem.classList.contains("blue")) { 
 
    elem.classList.remove("blue"); 
 
    elem.classList.add("green"); 
 
    } else { 
 
    elem.classList.remove("green"); 
 
    elem.classList.add("red");  
 
    } 
 
}
.red { background-color: red;} 
 
.blue {background-color: blue;} 
 
.green {background-color: green;}
<h1>Disco Inferno</h1> 
 
<div class="light red" id="light"> 
 
    div 
 
</div> 
 

 
<button onClick="ColorFunction()">Burn!</button>
지금 추가/제거를 가진 경우 체크를 할 수있는 다른 방법이 있습니다,하지만 기본적인 생각이다.

관련 문제