Как сделать, чтобы шарик оставался в блоке и не вылазил за границы
Нужно, чтобы шарик оставался в блоке и не вылазил за границы. Как максимально лаконично это сделать в коде? Именно используя jquery.
$(document).ready(function(){
var mobileCircle = $('#mobileCircle');
$('#wrapper').mousemove(function(e){
mobileCircle.css({'top': e.pageY,'left': e.pageX});
});
});
#wrapper {
background-color: white;
height: 480px;
width: 640px;
border: 2px solid black;
margin: auto;
}
#mobileCircle {
position: absolute;
background-color: green;
height: 50px;
width: 50px;
border-radius: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="top">
<div id="wrapper">
<div id="mobileCircle">
</div>
</div>
<script src="js/script.js"></script>
</body>
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Так попробуйте Идея следить за границами и следить чтоб элемент не двигался дальше границ
50 - диаметр круга
2 - толщина границы
480 - высота
640 - ширина
$(document).ready(function(){
var mobileCircle = $('#mobileCircle');
$('#wrapper').mousemove(function(e){
let top = Math.min(480 + this.offsetTop - 50 + 2, e.pageY);
let left = Math.min(640 + this.offsetLeft - 50 + 2, e.pageX);
top = Math.max(this.offsetTop + 2, top);
left = Math.max(this.offsetLeft + 2, left);
mobileCircle.css({'top': top,'left': left});
});
});
#wrapper {
background-color: white;
height: 480px;
width: 640px;
border: 2px solid black;
margin: auto;
}
#mobileCircle {
position: absolute;
background-color: green;
height: 50px;
width: 50px;
border-radius: 0px; // изменил окружность для наглядности
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="top">
<div id="wrapper">
<div id="mobileCircle">
</div>
</div>
<script src="js/script.js"></script>
</body>
Upd.
Fortunately, jQuery normalizes the .pageX and .pageY properties so that they can be used in all browsers. These properties provide the X and Y coordinates of the mouse pointer relative to the top-left corner of the document.
Так что нужно пересчитать относительно документа.