2011-09-20 139 views
0

任何想法,为什么这不会工作?当点击CTRL +向下箭头时,它应该使页面的背景颜色变暗。 (它开始于“#CCCCCC”。)Javascript变暗背景颜色

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

试试这个:

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; 

它改变颜色使得它总是不确定的范围。在调用color.length时会出现错误,因为undefined没有长度属性。将其更改为

color=r + g + b; 

编辑:

噢。演示:http://jsfiddle.net/EuShR/(FYI按ctrl-往下看效果)