day16
1- 什么是事件委托,原理是什么?
原理: 利用冒泡的原理,把事件加到父级上,触发执行效果。
2- js 中有几种定时器,有什么区别?
setTimeout() 和 setInterval()
setTimeout:一次性定时器,只在指定时间后执行一次;
setInterval以指定时间为周期循环执行
3- 如何清除定时器?
clearInterval()
clearTimeout()
4-封装一个动画函数
封装变速函数:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
div {
margin-top: 20px;
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
left: 0;
top: 0;
}
</style>
<body>
<input type="button" value="移动" id="btn">
<div id="dv"></div>
<script src="js/common.js"></script>
<script>
function getStyle(element, attr) {
// 判断浏览器是否指该属性
return window.getComputedStyle ? window.getComputedStyle(element, null)[attr] : element.currentStyle[attr]
}
// 点击按钮,可以改变宽高,位置,透明度,层级关系
function animate(element, json, fn) {
//清理定时器
clearInterval(element.timerId)
// 创建定时器
element.timerId = setInterval(function () {
// 创建标志位,确定定时器是否要清除
var flag = true;
for (var attr in json) {
if (attr == "opacity") { //透明度
// 获取元素透明度
var current = parseInt(getStyle(element, attr) * 100);
console.log(current)
// 计算变化步数
var target = json[attr] * 100;
var step = (target - current) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step)
current += step;
element.style[attr] = current / 100;
}
else if (attr == "z-Index") { //z-index属性
// 层级关系改变就是直接改属性值
element.style[attr] = json[attr]
}
else { // 普通属性
// 获取元素当前属性值
var current = parseInt(getStyle(element, attr))
// 移动步数(获取当前属性的目标值)
var target = json[attr];
// 确定移动步数,计算步长,达到缓动效果
var step = (target - current) / 10;
// 判断 取整
step = step > 0 ? Math.ceil(step) : Math.floor(step) //Math.ceil向上取整,Math.floor向下取整
current += step
element.style[attr] = current + "px";
}
// 判断目标是否到达位置
if (current != target) {
flag = false
}
}
if (flag) {
clearInterval(element.timerId)
if (fn) {
fn()
}
}
}, 20)
}
// 方法调用
getId("btn").onclick = function () {
var json1 = { "width": 800, "height": 400, "left": 500, "top": 600, "opacity": 0.1 }
animate(getId("dv"), json1, function () {
var json2 = { "width": 100, "height": 100, "left": 50, "top": 50, "opacity": 1, "z-Index": 1000 }
animate(getId("dv"), json2)
})
}
/* getId("btn").onclick = function () {
var json1 = { "width": 800, "height": 400, "left": 500, "top": 600, "opacity": 0.1 }
animate(getId("dv"), json1, function () {
var json2 = { "width": 100, "height": 100, "left": 50, "top": 50, "opacity": 1, "z-Index": 1000 }
animate(getId("dv"), json2)
})
} */
</script>
</body>
</html>


浙公网安备 33010602011771号