javascript - How to make a border? -
i have element
<div id="square"></div>
he has property move on document
var square = document.getelementbyid("square"); document.body.onkeydown = function(e) { if (e.keycode == 37) {left()} if (e.keycode == 38) {up()} if (e.keycode == 39) {right()} if (e.keycode == 40) {down()} }
how make function, not allowed movement, if square
element closest document border? jsfiddle: https://jsfiddle.net/zutxylsq/
you need check if left outside of boundaries this:
function left() { console.log('left'); var left = parseint(square.style.left || getcomputedstyle(square)['left'], 10); if (left >= 50) { square.style.left = (left - 50) + 'px'; } } function right() { console.log('right'); var left = parseint(square.style.left || getcomputedstyle(square)['left'], 10); if (left+50+square.offsetwidth < window.innerwidth) { square.style.left = (left + 50) + 'px'; } }
https://jsfiddle.net/zutxylsq/3/
and same , down.
Comments
Post a Comment