[英]How can I reference a variable from a js script in html
I've seen similar questions asked before but none of them really helped in my situation.我之前看过类似的问题,但没有一个对我的情况有帮助。 To boil it down I, a noobie, am trying to change an html background color to a variable that was created in a js script and I'm not sure quite how to do this.归根结底,我是一个菜鸟,正在尝试将 html 背景颜色更改为在 js 脚本中创建的变量,但我不太确定如何执行此操作。 I want "color" to be used for the background color.我希望“颜色”用于背景颜色。 h, m, s are hours minutes and seconds. h、m、s 是小时、分钟和秒。 I'm pulling these from the computer and it is working fine printing it.我正在从计算机中提取这些内容,并且打印效果很好。 Here is something I found that is nearly identical to what I want to do www.jacopocolo.com/hexclock/这是我发现的与我想做的几乎相同的事情www.jacopocolo.com/hexclock/
JS JS
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
$("div.background").css("background-color", color );
HTML HTML
<style>
.background {
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
I've tried making a div for the background (shown above) but it doesn't seem to be working.我试过为背景制作一个 div(如上所示),但它似乎不起作用。 In the end all I'm really set on is this part of it最后,我真正要做的就是这部分
if (h<=9) {h = '0'+h};
if (m<=9) {m = '0'+m};
if (s<=9) {s = '0'+s};
var color = '#'+h+m+s;
Can someone tell me how to properly do this or even just point me in the general direction?有人能告诉我如何正确地做到这一点,甚至只是指出我的大方向吗? Any help would be greatly appreciated.任何帮助将不胜感激。
I tried it, and it works fine.我试过了,效果很好。
$(document).ready(function(){ var h = 0; var m = 9; var s = 20; if (h<=9) {h = '0'+h} if (m<=9) {m = '0'+m}; if (s<=9) {s = '0'+s}; var color = '#'+h+m+s; console.log('color' + color); console.log("Original Color " + $("div.background").css('background-color')); $("div.background").css("background-color", color ); console.log("Updated Color " + $("div.background").css('background-color')); });
<html> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="app.js"></script> <style> .background { width: 100%; height: 100%; position: absolute; vertical-align: middle; } </style> </head> <body> <div class="background">hello world</div> </body> </html>
The problem in your code is probably that a color parameter pre-pended with '#' must be given in hexadecimal coordinates:您代码中的问题可能是必须以十六进制坐标给出以“#”开头的颜色参数:
red=10, green=20 and blue=40 should be written like this: red=10, green=20 and blue=40 应该这样写:
#0A1428
So, you have to convert first to hexadecimal each coordinate like this:因此,您必须首先将每个坐标转换为十六进制,如下所示:
var h = h.toString(16);
var m = m.toString(16);
var s = s.toString(16);
Then, perform the zero left-padding, and so.然后,执行零左填充,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.