en.javascript.info/02-ui/02-events-and-interfaces/03-obtaining-event-object/01-move-ball-field/solution/ball-move/index.html
Ilya Kantor f301cb744d init
2014-10-26 22:10:13 +03:00

93 lines
3 KiB
HTML
Executable file

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
#field {
width: 200px;
height: 150px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
overflow: hidden;
cursor: pointer;
}
#ball {
position: absolute;
left: 0;
top: 0;
width: 40px;
height: 40px;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
-ms-transition: all 1s;
transition: all 1s;
}
</style>
</head>
<body style="height:2000px">
Кликните на любое место поля, чтобы мяч перелетел туда.<br>
<div id="field">
<img src="http://js.cx/clipart/ball.gif" id="ball">
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>
<script>
var field = document.getElementById('field');
var ball = document.getElementById('ball');
field.onclick = function(event) {
// координаты поля относительно окна
var fieldCoords = this.getBoundingClientRect();
// координаты левого-верхнего внутреннего угла поля
var fieldInnerCoords = {
top: fieldCoords.top + field.clientTop,
left: fieldCoords.left + field.clientLeft
};
// разместить по клику,
// но сдвинув относительно поля (т.к. position:relative)
// и сдвинув на половину ширины/высоты
// (!) используются координаты относительно окна clientX/Y, как и в fieldCoords
var ballCoords = {
top: event.clientY - fieldInnerCoords.top - ball.clientHeight / 2,
left: event.clientX - fieldInnerCoords.left - ball.clientWidth / 2
};
// вылезает за верхнюю границу - разместить по ней
if(ballCoords.top < 0) ballCoords.top = 0;
// вылезает за левую границу - разместить по ней
if(ballCoords.left < 0) ballCoords.left = 0;
// вылезает за правую границу - разместить по ней
if(ballCoords.left + ball.clientWidth > field.clientWidth) {
ballCoords.left = field.clientWidth - ball.clientWidth;
}
// вылезает за нижнюю границу - разместить по ней
if(ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
ball.style.left = ballCoords.left + 'px';
ball.style.top = ballCoords.top + 'px';
}
</script>
</body>
</html>