01-定时器-延时器-广告案例
<style>
.box {
width: 600px;
height: 400px;
background-color: green;
text-align: center;
line-height: 400px;
/* margin: 100px auto; */
position: fixed;
left: 30%;
display: none;
}
</style>
</head>
<body>
<div class="box">
这是一个广告
<span>5</span>
</div>
<script>
// 用户打开页面3秒后,弹出一个广告
// 延时器
let res = setTimeout(function () {
// 1. 拿到元素:box,span
let box = document.querySelector('.box')
let span = box.lastElementChild
console.log(box, span)
// 2. 让box显示出来
box.style.display = 'block'
// 3. 开启定时器:span中的内容不断的减少到0
let timeId = setInterval(function () {
span.innerText--
// 4. 到0:结束定时器,将广告隐藏
if (span.innerText == 0) {
clearInterval(timeId)
box.style.display = ''
}
}, 1000)
}, 3000)
// 清理延时器
clearTimeout(res)
</script>
</body>
</html>
02-定时器-左右运动bug解决案例
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
left: 0;
top: 100px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<button class="to-right">向右移动到600</button>
<button class="to-left">向左移动到0</button>
<div class="box"></div>
<script>
// 需求:点击向左移动到0,盒子移动到0(到了0要停止)
// 获取到box元素
let box = document.querySelector('.box')
// 1. 给按钮to-right增加事件
// 全局变量可以解决元素多个定时器的问题:有缺陷
// 1. 如果页面必须有多个定时器就会出现问题:最终只有一个
// 2. 全局变量可以被污染
// 解决方案:将定时器存在元素自己身上(元素是一个对象,对象是引用传值:安全)
// let timeId
document.querySelector('.to-right').onclick = function () {
// 先清除可能存在的定时器
clearInterval(box.timeId)
// 2. 事件处理:给box做动画,改变left的值,每次改变10px,到600结束
box.timeId = setInterval(function () {
console.log(1)
box.style.left = box.offsetLeft + 11 + 'px'
if (box.offsetLeft >= 600) {
// 注意:如果是匀速运动,要考虑移动可能会超出目标值:修正
box.style.left = 600 + 'px'
clearInterval(box.timeId)
}
}, 20)
}
// 1. 给按钮to-left增加事件
document.querySelector('.to-left').onclick = function () {
// 先清除可能存在的定时器
clearInterval(box.timeId)
// 2. 事件处理:给box做动画,改变left的值,每次改变10px,到0结束
box.timeId = setInterval(function () {
console.log(1)
box.style.left = box.offsetLeft - 10 + 'px'
if (box.offsetLeft <= 0) {
// 注意:如果是匀速运动,要考虑移动可能会超出目标值:修正
box.style.left = 0 + 'px'
clearInterval(box.timeId)
}
}, 20)
}
// box是一个盒子:元素对象
box.index = 1 // 给box增加一个属性,值为1,非标准属性:点语法是不会进入元素本身(内存有效)
console.log(box.index)
</script>
</body>
</html>
注意:
// 1. 给按钮to-right增加事件
// 2.全局变量可以解决元素多个定时器的问题:有缺陷
// 3. 如果页面必须有多个定时器就会出现问题:最终只有一个
// 4. 全局变量可以被污染
// 解决方案:将定时器存在元素自己身上(元素是一个对象,对象是引用传值:安全)