Сделать в базисе c CSS.
#test {
position:absolute;
height: 70px;
width: 100px;
background-color: green;
border-radius: 50%;
display: inline-block;
}
#test:hover {
background-color : red;
}
<div id="test"></div>
Если вы хотите выполнить JS, когда элемент зависает, используйте .hover()
вместо click()
в вашем коде. Вы также можете определить, является ли точка в настоящее время красной или зеленой, с помощью if (div.style.backgroundColor == "red")
Этот код работает не так, как вы ожидаете, потому что я не понимаю, что вы хотите сделать именно так, но он должен дать ты и идеар.
$('#test').click(function() {
if (document.getElementById("test").style.backgroundColor != "green") {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.3 ? 'red' : 'green',
});
}
});
$('#test').hover(function() {
if (document.getElementById("test").style.backgroundColor == "green" && $('#test').is(":hover")) {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.3 ? 'red' : 'green',
});
}
});
#test {
position:absolute;
height: 70px;
width: 100px;
background-color: red;
border-radius: 50%;
display: inline-block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>