zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JSCSS to create Function INTO convert Numbers
2023-09-14 08:59:13 时间

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)