#javascript
Задача в том, что я не могу сделать так, чтобы мышь не доходила до блока. Нужно сделать
так, чтобы, например, при расстоянии 10px мыши от блока блок переместился.
var div = document.createElement('div');
div.className = "myDiv";
with(div.style) {
width = '100px';
height = '100px';
backgroundColor = 'red';
}
document.body.appendChild(div);
div.addEventListener("mousemove", draw);
div.addEventListener('mouseover', count);
function draw() {
this.style.left = Math.random() * document.body.clientWidth + 'px';
this.style.top = Math.random() * document.body.clientHeight + 'px';
mouseMove(event)
}
var x = 0;
function count() {
this.innerHTML = x += 1;
}
* {
margin: 0;
padding: 0;
position: relative;
}
Title
Ответы
Ответ 1
Пусть тогда документ сам следит за мышами - и как только они подберутся поближе - убирает всё ценное куда подальше. var cheese = document.querySelector('.cheese'); // За мышью следит сам документ: document.addEventListener("mousemove", mm); document.addEventListener('mouseover', mo); var border = 10; function mm(e) { if (e.clientX > cheese.offsetLeft - border && e.clientX < cheese.offsetLeft + cheese.offsetWidth + border && e.clientY > cheese.offsetTop - border && e.clientY < cheese.offsetTop + cheese.offsetHeight + border ) { // если мышь слишком близко - убираем сыр! cheese.style.left = Math.random()* (window.innerWidth - 30) + 'px'; cheese.style.top = Math.random() * (window.innerHeight - 30) + 'px'; } } function mo(e){ if (e.target === cheese) cheese.innerText = +(cheese.innerText || 0)+1; } * { margin: 0; padding: 0; position: relative; } .cheese { display: inline-block; width: 30px; height: 30px; background-color: yellow; }
Комментариев нет:
Отправить комментарий