代码如下(示例):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 800px;
height: 600px;
background-color: deepskyblue;
margin: 100px auto;
position: relative;
}
.dv {
width: 150px;
height: 150px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
border-radius: 50%;
}
</style>
</head>
<body>
<button>动起来</button>
<div class="box">
<div class="dv"></div>
</div>
</body>
<script>
function my$(selector, context) {
context = context || document
if (selector.indexOf('#') === 0) {
return document.getElementById(selector.slice(1))
}
if (selector.indexOf('.') === 0) {
return context.getElementsByClassName(selector.slice(1))
}
return context.getElementsByTagName(selector)
}
const btn = my$('button')[0],
box = my$('.box')[0],
dv = my$('.dv')[0]
btn.onclick = () => {
let speed = -5
let speed2 = -8
setInterval(function () {
let _left = parseFloat((css(dv, 'left')))
let _top = parseFloat(css(dv, 'top'))
if (_left >= box.offsetWidth - dv.offsetWidth || _left <= 0) {
speed *= -1
}
if (_top >= box.offsetHeight - dv.offsetHeight || _top <= 0) {
speed2 *= -1
}
dv.style.left = _left + speed + 'px'
dv.style.top = _top + speed2 + 'px'
// console.log(12)
}, 10)
}
</script>
</html>