console
window.onload = function() {
const btn = document.getElementById('btn')
const div = document.getElementById('move')
var time = null
var speed = 0
btn.onclick = function() {
startMove()
}
function startMove () {
clearInterval(time)
time = setInterval(function() {
speed += 3
var t = div.offsetTop + speed
if (t > document.documentElement.clientHeight - div.offsetHeight) {
t = document.documentElement.clientHeight - div.offsetHeight
speed *= -1
speed *= 0.75
}
div.style.top = t + 'px'
}, 80)
}
}
const H = document.documentElement.clientHeight
const W = document.documentElement.clientWidth
document.onkeydown=function(event){
const msg = document.getElementById('msg')
var e = event || window.event || arguments.callee.caller.arguments[0];
let offsetL = document.getElementById('box').offsetLeft
let offsetT = document.getElementById('box').offsetTop
let px = offsetL
let py = offsetT
msg.innerHTML = 'x:' + px +'--' + 'y:' + py
if (e && e.keyCode == 37) {
if (offsetL <= 0) return
document.getElementById('box').style.left = offsetL - 1 + 'px'
}
if (e && e.keyCode == 38) {
if (offsetT <= 0) return
document.getElementById('box').style.top = offsetT - 1 + 'px'
}
if (e.keyCode == 39) {
if (offsetL >= W - 50) return
document.getElementById('box').style.left = offsetL + 1 + 'px'
}
if (e && e.keyCode == 40) {
if (offsetT >= H - 50) return
document.getElementById('box').style.top = offsetT + 1 + 'px'
}
};
<div id="msg">
</div>
<div id="box"></div>
<button id="btn">click</button>
<div id="move"></div>
* {
padding: 0;
margin: 0
}
#box {
position: absolute;
left: 0;
top: 0;
z-index: 1;
width: 1px;
height: 1px;
background: red
}
#move {
position: absolute;
z-index: 88;
width: 50px;
height: 50px;
background: red
}