我找到了一个示例代码,用于在用户移动鼠标时更改正文的背景颜色,但第一次页面为白色。在移动鼠标之前,您无法看到更改。
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/
如何在加载时触发?
答案 0 :(得分:2)
工作示例:
$(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();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
您可以使用jquery的$(document).ready()
函数,在加载内容时调用该函数以初始设置随机背景颜色(或您想要的任何颜色)。
我更新了您的fiddle。
答案 2 :(得分:0)
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});
答案 3 :(得分:0)
您可以使用这种方法:
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);
}
});
});