要求:
跑马灯:
创建两个大盒子对象,让小盒子在大盒子持续按规律进行移动
1、点击“开始”按钮,开始移动
2、点击“停止按钮”,结束移动
静态布局:
<div class="big">
<div class="small"></div>
</div>
<button>开始</button>
<button>结束</button>
css样式:
<style>
* {
margin: 0;
padding: 0;
}
.big {
width: 500px;
height: 300px;
border: 1px solid black;
margin: 20px;
position: relative;
}
.small {
width: 50px;
height: 50px;
background-color: skyblue;
position: absolute;
}
button {
margin-right: 5px;
margin-left: 20px;
}
</style>
静态效果:
js代码:
<script>
//获取元素
var button = document.querySelectorAll("button")
var bigbox = document.querySelector(".big")
var smallbox = document.querySelector(".small")
var dsq;
//给按钮“开始”绑定事件
button[0].onclick = function () {
dsq = setInterval(function () {
//获取small的偏移量
var left1 = smallbox.offsetLeft
var top1 = smallbox.offsetTop
//获取small的移动最大值,减2为边框多出的2px
var maxX = bigbox.offsetWidth - smallbox.offsetWidth - 2
var maxY = bigbox.offsetHeight - smallbox.offsetHeight - 2
//分析情况
//small往右走
if (left1 < maxX && top1 == 0) {
smallbox.style.left = left1 + 10 + 'px'
left1 = smallbox.style.left
}
//small往下走
else if (top1 < maxY && left1 == 450) {
smallbox.style.top = top1 + 10 + 'px'
top1 = smallbox.style.top
}
//small往左走
else if (top1 > 0 && left1 > 0) {
smallbox.style.left = left1 - 10 + 'px'
left1 = smallbox.style.left
//small往上走
} else if (left1 == 0) {
smallbox.style.top = top1 - 10 + 'px'
top1 = smallbox.style.top
}
//100毫秒回调一次
}, 100)
}
//给结束按钮设置点击事件,当点击时,则清除定时器
button[1].onclick = function () {
clearInterval(dsq)
}
实现的效果:
跑马灯