Рандомнная позиция элемента на странице javascript
Есть html разметка:
<div class="map-location"></div>
Есть css стиль для него:
.map-location {
content: "";
position: absolute;
top: 20%;
left: 35%;
}
Задача:
Я хочу убрать с css top и left и блоку map-location присвоить атрибут style и в нем top и left задавать с рандомными значениями от 0 до 100.
Можно ли такое реализовать на JS? Прошу помощи в реализации.
Ответы (1 шт):
Автор решения: Daniil Loban
→ Ссылка
const rndBtn = document.querySelector('#rndBtn');
rndBtn.addEventListener('click', randomize, false )
function randomize(e) {
const max = 100;
loc = document.querySelector('.map-location');
loc.style.top = `${Math.floor(Math.random()*(max + 1))}%`
loc.style.left = `${Math.floor(Math.random()*max + 1)}%`
}
.map-location {
content: "";
position: absolute;
top: 20%;
left: 35%;
}
button{
position: relative;
top: 200px;
}
<!DOCTYPE html>
<html>
<head>
<title>Random point</title>
</head>
<body>
<div class="map-location">*</div>
<button id="rndBtn">Random</button>
</body>
</html>