要求:
跑马灯:
创建两个大盒子对象,让小盒子在大盒子持续按规律进行移动
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)
}
实现的效果:
跑马灯
这篇博客详细介绍了如何使用JavaScript来创建一个跑马灯效果,包括两个大盒子中的小盒子按规律移动。通过监听开始和结束按钮的点击事件,实现了小盒子在大盒子内的左右上下循环移动。当点击开始按钮时,设置定时器让小盒子按设定的路径移动;点击结束按钮则清除定时器,停止移动。示例代码中给出了HTML、CSS和JavaScript的具体实现。
效果&spm=1001.2101.3001.5002&articleId=126235152&d=1&t=3&u=2a31569c98d64b18a50be0ca19764fdd)
1576

被折叠的 条评论
为什么被折叠?



