Skip to content

Instantly share code, notes, and snippets.

@codingwithsara
Created August 9, 2019 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingwithsara/dce5dfac82be6dbbf95b17aa12ec2455 to your computer and use it in GitHub Desktop.
Save codingwithsara/dce5dfac82be6dbbf95b17aa12ec2455 to your computer and use it in GitHub Desktop.
JavaScript RGB to HEX converter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RGB to HEX Converter</title>
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<style>
/* 省略 */
</style>
<script>
function changeRange() {
// r,g,bの値を取得して、int型に変換する
var r = parseInt(document.getElementById("r").value);
var g = parseInt(document.getElementById("g").value);
var b = parseInt(document.getElementById("b").value);
// #20b9ff のように文字列を作成する
var color = "#" + hex(r) + hex(g) + hex(b);
// 背景色・テキストを変更する
document.body.style.backgroundColor = color;
document.getElementById("hex-label").innerText = color;
document.getElementById("r-label").innerText = r;
document.getElementById("g-label").innerText = g;
document.getElementById("b-label").innerText = b;
// 文字色の切り替え
if (r < 100 && g < 100 && b < 100) {
document.getElementById("container").style.color = "white";
} else {
document.getElementById("container").style.color = "black";
}
}
function hex(num) {
// 10進数を16進数に変換する
var hex = num.toString(16);
if (num < 16) hex = "0" + hex;
return hex;
}
</script>
</head>
<body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment