开发者

Javascript darken background color

开发者 https://www.devze.com 2023-04-05 20:08 出处:网络
Any idea why this wont work? It\'s supposed to darken the background color of a page when clicked CTRL+arrow down. (It starts off at \"#cccccc\".)

Any idea why this wont work? It's supposed to darken the background color of a page when clicked CTRL+arrow down. (It starts off at "#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;

    }


    }


Try this instead:

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+")";
    }
}


It's this nasty little piece of code:

var color=r + g + b;

it's changing the scope of color making it always undefined. This throws an error where you call color.length because undefined doesn't have a length property. Change it to

color=r + g + b;

EDIT:

oh yeah. demo: http://jsfiddle.net/EuShR/ (fyi press ctrl-down to see effect)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号