[英]Using the time as css background color
Just for fun, I wanted to make my website have a dynamic background color that's an rgb value based on the current time. 只是为了好玩,我想让我的网站具有动态背景颜色,该颜色是基于当前时间的rgb值。 I did some googling and came up with the following, but it's not working.
我做了一些谷歌搜索,并提出了以下建议,但是它没有用。
index.html index.html
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link type="text/javascript" src="date.js">
<style>
p{
font-size: 150%;
}
</style>
</head>
<body>
</body>
</html>
date.js date.js
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
}
document.getElementsByName("html").style.backgroundColor = "rgb(" + now + ")";
Can anyone help me with what I'm doing wrong, or an alternate/better way to do this? 谁能帮我解决我做错的事情,或者替代/更好的方法来解决这个问题? I apologize if I did something stupid, I'm quite a javascript noob
如果我做了一些愚蠢的事情,我表示歉意,我是一个纯JavaScript的菜鸟
Thanks in advance 提前致谢
Your last line is out of function. 您的最后一行不起作用。 And
document.getElementByName
doesn't work for html
tag you should use document.getElementByTagName
. 而且
document.getElementByName
不适用于html
标记,您应该使用document.getElementByTagName
。
Overal use this instead 总体上用这个代替
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime(field) {
var now = new Date();
now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4);
$(field).val(now);
$('body').css('background-color', "rgb(" + now + ")");
}
Here. 这里。 All jQuery.
所有的jQuery。 Code modified to work.
修改代码即可正常工作。
$(document).ready(function() { setInterval(function(){currentTime("#idTimeField")}, 500); }); function currentTime(field) { var now = new Date(); now = (now.getHours() * 10) + ', ' + (now.getMinutes() * 4) + ', ' + (now.getSeconds() * 4); $(field).val(now); $('html,body').css({'background-color':'rgb('+now+')'}); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <title>Site</title> <link rel="stylesheet" type="text/css" href="style.css"> <link type="text/javascript" src="date.js"> <style> p{ font-size: 150%; } </style> </head> <body> <div id="idTimeField">20:10:34</div> </body> </html>
How about something like this: 这样的事情怎么样:
$(document).ready(function() {
setInterval(function(){currentTime("#idTimeField")}, 500);
});
function currentTime() {
var now = new Date();
var R = (now.getHours() * 10) ;
var G = (now.getMinutes() * 4) ;
var B = (now.getSeconds() * 4);
document.body.style.backgroundColor = 'rgb(' + [R,G,B].join(',') + ')';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.