請求動畫幀
setTimeout(fn,1000)
缺點是不準時 會受到頁面的影響 當代碼多的時候就會一卡一卡
requestAnimationFrame 請求動畫幀
requestAnimationFrame(function () {
console.log(1);
})
與setTimeout類似,但是不能設置時間 根據瀏覽器刷新頻率執行 重繪多少次就執行多少次
var date =new Date();
var n=0;
function animationFps(){
if (new Date().getTime()- date >= 1000){
console.log(n)
}else{
n++;
requestAnimationFrame(animationFps);
}
}
animationFps();
結果打印是61 屏幕1秒刷新次數
cancelAnimationFrame() 刪除動畫幀 傳的是動畫幀的變量名 ie9及以下不支持
var timer,n=0;
fn();
function fn() {
console.log(n++);
requestAnimationFrame(fn);
}
這樣就會一直打印不會停下來
function fn() {
console.log(n++);
timer =requestAnimationFrame(fn);
}
document.onclick =function () {
cancelAnimationFrame(timer);
}
停止打印
兼容寫法
window.requestAnimationFrame =window.requestAnimationFrame||function (callback) {
return setTimeout(callback,1000/60);
}
請求動畫幀兼容
window.cancelAnimationFrame=window.cancelAnimationFrame||clearTimeout;
取消動畫幀
速度版運動框架
function animation(ele,attr,value,step,callback) { }
ele是元素節點 attr是屬性值 value是具體數值 step是步長,每次要改變的數值 callback是回掉函數
<style>
div{
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
var box =document.querySelector(".box");
animation(box,"width",500,10);
function animation(ele,attr,value,step,callback) {
var start = parseFloat(getstyle(ele)[attr]);
function fn() {
if (start>=value){
start=value
}else{
start+=step;
ele.style[attr]=start+"px";
requestAnimationFrame(fn);
}
}
fn();
}
//獲取css屬性值
function getstyle(ele) {
return ele.currentStyle||getComputedStyle(ele);
}
</script>
刷新的話就會執行 缺點是 只能是增加這個方向 不能反方向
var box =document.querySelector(".box");
animation(box,"width",500,10);
function animation(ele,attr,value,step,callback) {
var direction =start>value;//判斷方向
if (direction){
step/=-1;
}
var start = parseFloat(getstyle(ele)[attr]);
function fn() {
if (direction?start<=value:start>=value){//當方向改變時判斷也要相應改變
start=value;
ele.style[attr]=start+"px";
}else{
start+=step;
ele.style[attr]=start+"px";
requestAnimationFrame(fn);
}
}
fn();
}
//獲取css屬性值
function getstyle(ele) {
return ele.currentStyle||getComputedStyle(ele);
}
可以增加或減少兩個方向
var box =document.querySelector(".box");
animation(box,"width",500,10,function () {
animation(this,"height",300,10,function () {
animation(this,"marginLeft",100,10)
})
});
function animation(ele,attr,value,step,callback) {
var direction =start>value;
if (direction){
step/=-1;
}
var start = parseFloat(getstyle(ele)[attr]);
function fn() {
if (direction?start<=value:start>=value){
start=value;
ele.style[attr]=start+"px";
callback&&callback.call(ele);
}else{
start+=step;
ele.style[attr]=start+"px";
requestAnimationFrame(fn);
}
}
fn();
}
//獲取css屬性值
function getstyle(ele) {
return ele.currentStyle||getComputedStyle(ele);
}
可以連續改變多個css屬性值