1.函数的节流
在一定的时间内函数只运行一次
//1. 函数节流
var canMove = true ;
document.querySelector(".box1").onmousemove = function(){
//每次执行函数判断变量是否为true,true则可以执行函数的逻辑代码
if (canMove){
canMove = false ;
setTimeout(function(){
canMove =true;
},1000);
console.log("onmousemove");
}
}
2.函数防抖
有足够的空闲时间去执行函数
:窗口滚动条滚动触发的事件,由于滚动事件一般是滚动停止后才执行函数,可以选择函数防抖
//2.函数防抖
//滚动条
window.onscroll = function(e){
//定义一个定时器的索引变量
var setIndex = "";
clearTimeout(setIndex);
setIndex = setTimeout(function(){
console.log("scroll");
},500);
}
3.动画
<style>
.box1,.box2{
//设置动画用绝对定位定盒子的位置
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: pink;
}
.box2{
margin-top: 200px;
background-color: skyblue;
}
</style>
3.1用定时器做动画(不推荐使用)
由于每次都会触发重构和重绘,有时会有卡顿现象。
<script>
var box = document.querySelector(".box1");
var num = 0;
//3.1 用定时器做动画 因为每次都会触发重构和重绘,会出现卡顿现象
function animate(){
num += 10;
//盒子的样式设置
box.style.left = num + "px";
if(num < 500){
setTimeout(animate,100);
}
}
animate();
</script>
3.2 requestAnimationFrame (推荐使用)
基本介绍:
window.requestAnimationFrame(函数)
间隔时间是固定的 1000/电脑屏幕刷新率 (一般是60)
优点:
1.会把每一帧的DOM操作集中起来 在一次重绘或者回流中完成
2.在隐藏或不可见的元素中,不会重绘或者回流
<script>
var box2 =document.querySelector(".box2")
var num = 0;
(function animate2(){
num += 10 ;
box2.style.left = num + "px";
if (num < 500){
window.requestAnimationFrame(animate2);
}
})()
</script>