Показать сообщение отдельно
  #2 (permalink)  
Старый 02.08.2024, 10:24
Аватар для ksa
ksa ksa вне форума
CacheVar
Отправить личное сообщение для ksa Посмотреть профиль Найти все сообщения от ksa
 
Регистрация: 19.08.2010
Сообщений: 14,201

Сообщение от Димитр
В массиве все элементы = 0. При клике по квадрату в сетке grid получаем ID Diva и в этой координате вокруг значения элементов меняются на 3.
Предложу такой вариант...

<style>
*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
.wrapper {
	display: grid;
	width: 220px;
	height: 220px;
}
#grid {
	display: grid;
	grid-template-columns: repeat(5, auto);
	grid-template-rows: repeat(5, auto);
	width: 220px;
	height: 220px;
}
#grid > div {
	height: 42px;
	width: 42px;
	background-color: #38d929;
	border: solid 1px white;
}
</style>

<div class="wrapper">
	<div id="grid"></div>
</div>


<script>
const arr = Array.from({length: 5}, _ => new Array(5).fill(0))
arr.forEach((a, i) => a.forEach((_, j) => {
	const o = document.createElement('div')
	o.dataset.i = i
	o.dataset.j = j
	grid.insertAdjacentElement('beforeend', o)
}))
grid.addEventListener('click', e => {
	const o = e.target.closest('[data-i]')
	if (!o) return
	const r = +o.dataset.i
	const c = +o.dataset.j
	for (let i = r - 1; i <= (r + 1); i++) {
		for (let j = c - 1; j <= (c + 1); j++) {
			if (i === r && j === c) continue
			if (arr[i][j] === undefined) continue
			arr[i][j] = 3
			grid.querySelector(`[data-i='${i}'][data-j='${j}']`).textContent = 3
		}
	}
})

</script>
Ответить с цитированием