CSS/Cookbook

【CSS/Cookbook】Making HTML Random Color Code(HTML 랜덤 색상 만들기)

1Q74 2023. 3. 16. 12:26

1. Description

JavaScript의 Math함수를 이용하여 난수를 발생시키고, 제한값을 0xFFFFFF로 설정한다.


2. Example

[Click Me]버튼을 클릭할 때마다 Box의 배경색이 랜덤색상으로 변경된다.


[1q74.tistory.com] css/div/table


[HTML Code]
[//HTML Code]

3. Code

더보기
<!-- ---------------------------------------------------------
  --
  -- Author: 1q74.tistory.com
  --
  --------------------------------------------------------- -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>[1q74.tistory.com] css/div/table</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>

	<div name="_1q74-example-root">
		<div name="_1q74-example-1">
		</div>

		<div name="_1q74-example-bottom">
			<br/>
			<button name="btn-execute">Click Me</button>
		</div>

		<script>
		var btnExecute = $("[name='_1q74-example-bottom'] [name='btn-execute']");
		var box = $("[name='_1q74-example-1']");

		btnExecute.click(function() {
			const numberLimit = parseInt(0xFFFFFF, 10);
			const randomNumber = Math.random() * numberLimit;
			const randomColorCode = "#" + Math.ceil(randomNumber).toString(16);
			box.css("background", randomColorCode).text(randomColorCode);	
		});
		</script>
	</div>

	<!--------------- [HTML Code] --------------->
	<hr/>
	<h5>[HTML Code]</h5>
	<div name="_1q74-source">
	</div>
	<h5>[//HTML Code]</h5>
	<!--------------- [//HTML Code] --------------->

<script>
// ------------------------------------------------------
// 소스출력
// ------------------------------------------------------
var textSource = $("[name='_1q74-source']");
var exampleHtml = $("[name='_1q74-example-root']").html();
var specialCharLines = textSource.text(exampleHtml).html().split("\n");
textSource.html(specialCharLines.join("<br/>").replaceAll("\t", "&nbsp;&nbsp;"));
</script>

<style>
[name="_1q74-example-1"] {
	display: block;
	width: 200px;
	height: 200px;
	border: 2px solid black;
}

[name|="_1q74-example"] button
,[name="_1q74-source"] button {
	background: lightgray;
	border: 5px outset;
	min-height: 40px;
}

[name|="_1q74-example"] button:active
,[name="_1q74-source"] button:active {
	border: 2px inset;
	min-height: 40px;
}
</style>
</body>
</html>

4. File

[css][div][table]random-color.html
0.00MB