I want to change the background color based on the position of the mouse

Here is my code:

$(document).mousemove(function(e){
    var $width = ($(document).width())/255;
    var $height = ($(document).height())/255;
    var $pageX = e.pageX / $width;
    var $pageY = e.pageY / $height;
    $("body").css("background-color", "rgb("+$pageX+","+$pageY+","+$pageX+")");
}); 

This kind of work, except that mousemove does not seem to be updated every time it moves. It seems to be lagging, are there any settings that I am missing? Pages x and page y are multiplied by the relative size of the documents up to 255, so the whole spectrum is used. Thank.

+5
source share
2 answers

Probably because you are coming back.

Try:

var $pageX = parseInt(e.pageX / $width,10);
var $pageY = parseInt(e.pageY / $height,10);

JsFiddle example

+8
source

, , , , . . - :

var w = Math.round($(document).width() / 255);
var h = Math.round($(document).height() / 255);
var body = $("body");

$(document).mousemove(function(e){
    var pageX = Math.round(e.pageX / w);
    var pageY = Math.round(e.pageY / h);
    body.css("background-color", "rgb("+pageX+","+pageY+","+pageX+")");
}); 

, , " " , reset w h.

jquery:

body.style.backgroundColor = "rgb("+pageX+","+pageY+","+pageX+")";
+1

All Articles