Created
January 29, 2019 14:29
-
-
Save sealucky7/867459d3c6ba26789d889db4f7d506b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
#field { | |
margin: 50px; | |
width: 200px; | |
height: 150px; | |
border: 10px groove black; | |
background-color: #00FF00; | |
position: relative; | |
overflow: hidden; | |
cursor: pointer; | |
} | |
#ball { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
width: 40px; | |
height: 40px; | |
} | |
</style> | |
<--- HTML -----> | |
<div style="min-height: 2000px"> | |
Кликните на любое место поля, чтобы мяч перелетел туда. | |
<br> Мяч никогда не вылетит за границы поля. | |
<div id="field"><img src="https://js.cx/clipart/ball.svg" id="ball">. . . . . . . . . . . . . . . . . . . . . . . . . . . . | |
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | |
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | |
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .</div> | |
</div> | |
<-------- Js -----------> | |
class FieldWithBall { | |
constructor(options) { | |
this._el = options.el; | |
this._ball = this._el.querySelector('#ball'); | |
this._maxX = this._el.clientWidth - this._ball.clientWidth; | |
this._maxY = this._el.clientHeight - this._ball.clientHeight; | |
this._el.addEventListener('click', this._onFieldClick.bind(this)); | |
} | |
_onFieldClick(event) { | |
let position = this._el.getBoundingClientRect(); | |
let x = event.clientX - position.left - this._el.clientLeft - this._ball.clientWidth / 2; | |
let y = event.clientY - position.top - this._el.clientTop - this._ball.clientHeight / 2; | |
x = Math.max(x, 0); | |
x = Math.min(x, this._maxX); | |
y = Math.max(y, 0); | |
y = Math.min(y, this._maxY); | |
this._ball.style.left = x + 'px'; | |
this._ball.style.top = y + 'px'; | |
} | |
} | |
new FieldWithBall({ | |
el: document.querySelector('#field') | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment