简体   繁体   中英

Change gradient background colors on mouse move

I'm attempting to have a gradient whose top and bottom colors are changed based on cursor position. The below function works when using $(document.body).css('background','rgb('+rgb.join(',')+')'); to change the background but I cannot seem to get it working with a gradient. The below code is what I have set up for testing in Firefox. I will update the code while I currently try to set it up with options for each browser.

http://coreytegeler.com/justin/

$(window).load(function(){
var $win = $(window),
    w = 0,h = 0,
    top = [],
    bottom = [],
    getWidth = function() {
        w = $win.width();
        h = $win.height();
    };

$win.resize(getWidth).mousemove(function(e) {

    top = [
        Math.round(e.pageX/w * 255),
        Math.round(e.pageY/h * 255),
        150
    ];

     bottom = [
        Math.round(e.pageX/h * 255),
        Math.round(e.pageY/w * 255),
        150
    ];

    $(document.body).css('background: -moz-linear-gradient(top, ('+top.join(',')+'), ('+bottom.join(',')+'))');
}).resize();

});

One problem is that you're using the javascript .css method wrong. It takes two parameters, or an object. So it should be:

$(document.body).css('background', '-moz-linear-gradient(top, rgb('+top.join(',')+'), rgb('+bottom.join(',')+'))');

or

$(document.body).css({background : '-moz-linear-gradient(top, rgb('+top.join(',')+'), rgb('+bottom.join(',')+'))'});

Apart from that your code looks largely correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM