【JavaScript】實現彩色格子效果

效果預覽:https://sevlt.github.io/color-grid/index.html

Html 代碼:

<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="stylesheet" href="./style.css" />
		<title>Color Grid</title>
	</head>
	<body>
		<div id="container"></div>
		<script src="./main.js"></script>
	</body>
</html>

CSS 代碼:

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
body {
	background: #111;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100vh;
}
#container {
	display: flex;
	align-items: center;
	justify-content: center;
	flex-wrap: wrap;
	max-width: 500px;
}
.square {
	background: #1d1d1d;
	box-shadow: 0 0 2px #000;
	margin: 2px;
	width: 16px;
	height: 16px;
	transition: all 2s;
}
.square:hover {
	transition-duration: 0s;
}
 

JavaScript 代碼:

var container = document.getElementById('container')
var colors = ['#e74c3c', '#8e44ad', '#3498db', '#e67e22', '#2ecc71']

var colorTotal = 700
for (let i = 0; i < colorTotal; i++) {
	let square = document.createElement('div')
	square.classList.add('square')
	square.addEventListener('mouseover', () => {
		setColor(square)
	})
	square.addEventListener('mouseout', () => {
		removeColor(square)
	})
	container.appendChild(square)
}

function setColor(element) {
	let color = getRndomColor()
	element.style.background = color
	element.style.boxshadow = `0 0 2px ${color}`
}
function removeColor(element) {
	element.style.background = '#1b1b1b'
	element.style.boxshadow = `0 0 2px #000`
}
function getRndomColor() {
	return colors[Math.floor(Math.random() * colors.length)]
}

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章