简体   繁体   中英

Change background color on mouse move and page load as well

I found a sample code which is change the background colour of the body when the user moves the mouse, but the first time the page is white. You can't see the changes until you move the mouse.

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

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

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

    $(document.body).css('background','rgb('+rgb.join(',')+')');

}).resize();

JSFiddle: http://jsfiddle.net/WV8jX/

How can I trigger on load?

Working Example:

 $(document).ready(function () { getRandomColor(); RandomMouseMoveColor(); }); function getRandomColor() { document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16); } function RandomMouseMoveColor() { var $win = $(window), w = 0,h = 0, rgb = [], getWidth = function() { w = $win.width(); h = $win.height(); }; $win.resize(getWidth).mousemove(function(e) { rgb = [ Math.round(e.pageX/w * 255), Math.round(e.pageY/h * 255), 150 ]; $(document.body).css('background','rgb('+rgb.join(',')+')'); }).resize(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can use jquery's $(document).ready() function, which get's called when the content is loaded to initially set a random background-color (or whatever color you want).

I updated your fiddle .

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

function colorize(e){  
    rgb = [
        Math.round(e.pageX/w * 255),
        Math.round(e.pageY/h * 255),
        150
    ];

    $(document.body).css('background','rgb('+rgb.join(',')+')');
}

$win.resize(getWidth).mousemove(colorize).resize();
colorize({pageX:0,pageY:0});

You can use such approach:

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

function changeColor(e) {
  rgb = [
    Math.round(e.pageX / w * 255),
    Math.round(e.pageY / h * 255),
    150
  ];

  $(document.body).css('background', 'rgb(' + rgb.join(',') + ')');
}

$win.resize(getWidth).mousemove(function(e) {
  changeColor(e);
}).resize();

$(document).ready(function() {
  var is_loaded = false;
  $(document.documentElement).bind("mouseover", function(e) {
    if (!is_loaded) {
      is_loaded = true;
      changeColor(e);
    }
  });
});

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