js简单运动框架--2 多属性运动

本文展示了一个简单的JavaScript运动框架,用于实现元素的多属性平滑运动,如透明度、高度和宽度的变化。当鼠标悬停在元素上时,元素将平滑地改变其透明度、高度和宽度,鼠标移开时则恢复原状。框架使用了setInterval进行动画更新,并在运动结束时调用回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>运动框架</title>
  <style type="text/css">
  *{margin: 0;padding: 0}
  div{width: 100px;height: 100px;background-color: red; margin: 10px;opacity: 0.3}
  </style>
  <script>
         function getStyle(obj,attr){
         if(obj.currentStyle){
          return obj.currentStyle[attr];
         }else{
          return getComputedStyle(obj,false)[attr];
         }
     }
     function startMove(obj,json,fn){
        clearInterval(obj.timer);
          obj.timer=setInterval(function(){
            var bStop=true; //所有运动都已经完成
            for(var attr in json){
              
              //1.取当前样式值
              var icur=0;
              if(attr=="opacity"){
                icur=parseInt(parseFloat(getStyle(obj,attr))*100);
              }else{
                  icur=parseInt(getStyle(obj,attr));
              }
              //2.计算速度
              var iSpeed=(json[attr]-icur)/8;
              iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed); 
              //3.检测停止    
              if(icur!=json[attr]){
                bStop=false;
              }


              if(attr=="opacity"){
                obj.style.filter="alpha(opacity:"+(icur+iSpeed)+")";//兼容老IE
                obj.style.opacity=(icur+iSpeed)/100;
              }else{


                obj.style[attr]=icur+iSpeed+'px';
              }


            }
            if(bStop){
              clearInterval(obj.timer);
              fn && fn();
            }
        },30);   


     };
     //以上可以封装为move.js,满足多属性运动
     window.οnlοad=function(){
      var oDiv=document.getElementById("div1");
      oDiv.οnmοuseοver=function(){
          startMove(oDiv,{opacity:100, height:200,width:200},function(){
            alert("ok");
          });
      }
      oDiv.οnmοuseοut=function(){
          startMove(oDiv,{opacity:50,height:100,width:100});
      }
     }
  </script>
	</script>
</head>
<body>
	<div id="div1"></div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值