2011-09-20 2 views
0

왜 이런 식으로 작동하지 않는지 알 수 있습니까? Ctrl + 화살표를 클릭하면 페이지의 배경색이 어두워집니다. (그것은 "#CCCCCC"에서 시작합니다.)자바 스크립트 배경색이 어두움

var color="cccccc"; 

    var isCtrl = false; 
    document.onkeyup=function(e){ 
    if(e.which == 17) isCtrl=false; 
    } 
    document.onkeydown=function(e){ 
    if(e.which == 17) isCtrl=true; 

    if(e.which == 40 && isCtrl == true) { 


    if (color.length >6) { color= color.substring(1,color.length)} 
    var rgb = parseInt(color, 16); 
    var r = Math.abs(((rgb >> 16) & 0xFF)+1); if (r>255) r=r-(r-255); 
    var g = Math.abs(((rgb >> 8) & 0xFF)+1); if (g>255) g=g-(g-255); 
    var b = Math.abs((rgb & 0xFF)+1); if (b>255) b=b-(b-255); 
    r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16); 
    if (r.length == 1) r = '0' + r; 
    g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16); 
    if (g.length == 1) g = '0' + g; 
    b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16); 
    if (b.length == 1) b = '0' + b; 
    var color=r + g + b; 

    document.body.style.backgroundColor="#"+color; 

    } 


    } 
+0

가 발생하는 경우 바로 당신이는 document.body에 설정하려고 라인 전에 경고 (컬러). style.backgroundColor? –

답변

2

대신이 시도 (참고로 효과를 볼 수 Ctrl 키 다운을 누르십시오) :

var color = 204; // "cc" in decimal; 

document.documentElement.onkeydown = function(e) { 
    e = e || window.event; 
    var c = e.which || e.keyCode; 
    if(c == 40 && e.ctrlKey) { 
     color = Math.max(color-8,0); 
     document.body.style.backgroundColor = "rgb("+color+","+color+","+color+")"; 
    } 
} 
2

그것은 코드의이 불쾌한 작은 조각 : 그것은 항상 정의되지 않은 만드는 색상의 범위를 변화하고

var color=r + g + b; 

. undefined에 length 속성이 없으므로 color.length을 호출하면 오류가 발생합니다.

color=r + g + b; 

편집에 변경 :

을 오, 그래. 데모 : http://jsfiddle.net/EuShR/