<style>
#box {
width: 400px;
height: 400px;
border: 1px solid #000000;
margin: 50px auto;
position: relative;
}
#ball {
height: 30px;
width: 30px;
border-radius: 50%;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
#block {
width: 100px;
height: 20px;
position: absolute;
left: 150px;
bottom: 0;
background-color: black;
}
</style>
<div id="box">
<div id="ball"></div>
</div>
<script>
var oBall = document.querySelector('#ball');
var oBox = document.querySelector('#box');
var maxLeft = oBox.clientWidth - oBall.offsetWidth;
var maxTop = oBox.clientHeight - oBall.offsetHeight;
var speedX = 3;
var speedY = 4;
setInterval(function () {
var left = oBall.offsetLeft;
var top = oBall.offsetTop;
left += speedX;
top += speedY;
if(left < 0 || left > maxLeft) {
speedX = -speedX
}
if(top < 0 || top > maxTop) {
speedY = -speedY
}
oBall.style.left = left + 'px';
oBall.style.top = top + 'px';
}, 10);
</script>