鼠标移动时更改渐变背景颜色

Change gradient background colors on mouse move

本文关键字:渐变 背景 颜色 移动 鼠标      更新时间:2023-09-26

我正在尝试一个渐变,它的顶部和底部颜色会根据光标位置进行更改。下面的函数在使用$(document.body).css('background','rgb('+rgb.join(',')+')');更改背景时有效,但我似乎无法使用渐变。下面的代码是我为在Firefox中进行测试而设置的。我将在当前尝试为每个浏览器设置选项时更新代码。

$(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();
});

一个问题是您错误地使用了javascript .css方法。它需要两个参数或一个对象。所以应该是:

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

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

除此之外,您的代码看起来基本正确。