一些简单在开发中用到的封装函数

1.返回当前样式的函数  

   function getStyle(obj,attr){//谁的属性

if(obj.currentStyle){
return obj.currentStyle[attr];//返回传递过来的某个属性
}
else{
return window.getComputedStyle(obj,null)[attr];
}

                }

   

 2.封装自己的从class类

   function getClass(classname){
if(document.getElementsByClassName){
return document.getElementsByClassName(classname);
}
var arr = [];
var dom = document.getElementById("*");
for(var i = 0;i<dom.length;i++){
if(dom[i].className == classname){
arr.push(dom[i]);
}
}
return arr;
}

3.封装运动框架基本函数

              <button id="btn1">200</button>
<button id="btn2">400</button>
<div id="box"></div>
</body>
<script>
var btn200 = document.getElementById("btn1");
var btn400 = document.getElementById("btn2");
var box = document.getElementById("box");
btn200.onclick = function(){
animate(box,{width:600,top:200,left:200});
}
btn400.onclick = function(){
animate(box,{width:400,top:500,opacity:40,zIndex:3},function(){alert("回调函数");});
}
//封装单个属性的运动框架,送什么属性,就改什么属性;
function animate(obj,json,fn){//给谁就是对象是谁,json对象;
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var flag = true;//用来判断是否停止计时器,必须写到遍历外边;
//开始遍历 json
for(var attr in json){//attr为属性,json[attr]为属性值
//计算步长   用target位置减去当前位置,除以10
//因为透明度和z-index的值不能加px单位,所以先判断一次
var current = 0;
if(attr == "opacity"){
//如果属性值为透明度,就获得透明度为0.4,没有就是为0,但是小数对于相减的操作不好操作
//所以有必要进行数据的处理
current = parseInt(getStyle(obj,attr)*100)|| 0;
console.log(current);
}
else{
//其他情况都是数值了
current = parseInt(getStyle(obj,attr));
}

//console.log(current);
//目标位置 其实就是属性值
var step = (json[attr] - current)/10;
step = step>0?Math.ceil(step):Math.floor(step);
//一旦有透明度输入, 就需要判断透明度
if(attr == "opacity"){
if("opacity" in obj.style){//判断浏览器是否支持opac
obj.style.opacity = (current + step)/100;
}
else{
obj.style.filter = "alpha(opacity = "+(current + step)* 10+")";
}
}
else if(attr == "zIndex"){
                            obj.style.zIndex = json[attr];
                        }


else{//其他情况排除后,就是指的left等;
obj.style[attr] = current + step +"px";
}
if(current != json[attr]){//只要其中一个不满足条件就不应该停止计时器,这句必须在遍历里面
flag = false;
}
}
if(flag){
clearInterval(obj.timer);
console.log("清楚计时器了,准备回调函数");
if(fn){//当定时器停止了,动画就结束了,如果有回调函数,就执行回调;
fn();//函数名 + () 就是调用函数;
}
}
},30);
}


        function getStyle(obj,attr){//谁的属性
if(obj.currentStyle){
return obj.currentStyle[attr];//返回传递过来的某个属性
}
else{
return window.getComputedStyle(obj,null)[attr];
}
}
</script>










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值