[CSS 3 + JS] Create a Function to Convert JS Numbers into CSS Hex Colors

JavaScript numbers and CSS hexadecimal numbers don't play very well together. You can solve this with a conversion function that takes the number, converts it to a string, then pads the string with the necessary zeroes at the start using padStart.

 

let blue = 0x0000ff
let green = 0x00ff00
let red = 0xff0000

console.log(255 === 0xff)

let toHex = color =>
  `#${color.toString(16).padStart(6, "0")}`

document.body.style.backgroundColor = toHex(red)

 

 

posted @ 2020-07-27 16:09  Zhentiw  阅读(91)  评论(0)    收藏  举报