简体   繁体   中英

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. I want "color" to be used for the background color. h, m, s are hours minutes and seconds. 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/

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

<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. 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:

#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.

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