发布时间:2022-11-19 14:00
VID_20220713_163005
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<style>
#div {
height: 50px;
width:80px;
background-color: red;
}
style>
<script>
//获取样式
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return window.getComputedStyle(obj,false)[attr];
}
}
/*
obj:元素对象
attr:属性 宽、高、背景色、透明度等
bConstSpeed:是否匀速。
zoomFactor:缩放系数
fnCallBack:回调函数
*/
function animal(obj,attr,iTarget,bConstSpeed=false,zoomFactor=null,fnCallBack=null){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
let iCurent=0;
if(attr=='opacity'){
iCurent=parseInt(getStyle(obj,attr)*100);
}else{
iCurent=parseInt(getStyle(obj,attr));
}
zoomFactor=zoomFactor||8;
let iSpeed=bConstSpeed?zoomFactor:(iTarget-iCurent)/zoomFactor;
iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed)
if(bConstSpeed){
/*匀速的停止条件 距离靠近目标值 距离足够近 */
if(Math.abs(iTarget-iCurent)<=iSpeed){
clearInterval(obj.timer);
if(attr=='opacity'){
obj.style.filter='alpha(opacity='+(iCurent+iSpeed)+')';
obj.style[attr]=(iCurent+iSpeed)/100;
}else{
obj.style[attr]=iTarget+'px';
}
if(fnCallBack){
fnCallBack();
}
}else{
obj.style[attr]=iCurent+iSpeed+'px';
}
}else{
//缓冲运动:两点重合
if(iCurent==iTarget){
clearInterval(obj.timer);
if(fnCallBack){
fnCallBack();
}
}else{
if(attr=='opacity'){
obj.style.filter='alpha(opacity='+(iCurent+iSpeed)+')';
obj.style[attr]=(iCurent+iSpeed)/100;
}else{
obj.style[attr]=iCurent+iSpeed+'px';
}
}
}
},30)
}
window.onload=function(){
var ele=document.querySelector('#div');
var btn1=document.querySelector('#btn1');
var btn2=document.querySelector('#btn2');
btn1.onclick=function(){
// animal(ele,'width',300,false,20,function(){
// animal(ele,'height',300)
// })
animal(ele,'opacity',10)
}
btn2.onclick=function(){
animal(ele,'height',50,false,null,function(){
animal(ele,'width',80,false,20)
})
}
}
script>
<div id="div">
div>
<button id="btn1">运动1button>
<button id="btn2">运动2button>
body>
html>