zoukankan      html  css  js  c++  java
  • js实现多物体运动框架并兼容各浏览器

    首先,我们须要知道在js中获取对象的宽度如offsetWidth等。可能会存在一些小小的bug。原因之中的一个在于offsetWidth只不过获取盒子模型中内容的部分宽度。并不包括内边距,边框和外边距。这样会导致控制对象运动与预期不符。这里就不具体的去解释。

    而为了解决问题。在这里。我们提供了一个方法来保证我们的运动的准确性。


    style仅仅能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。


    currentStyle能够弥补style的不足。可是仅仅适用于IE。
    getComputedStyle同currentStyle作用同样,可是适用于FF、opera、safari、chrome。

    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8"/>
    	<style type="text/css">
          #div1,#div2{ 200px;height: 100px;background: #800808;margin-bottom: 2em;}
    	</style>
    	<script type="text/javascript">
    	window.onload=function(){
    		var oDiv=document.getElementsByTagName('div');
    		var oDiv1=document.getElementById('div1');
    		var oDiv2=document.getElementById('div2');
    		for(var i=0;i<oDiv.length;i++)
    		{
    			oDiv[i].timer=null;
    			oDiv1.onmouseover=function(){
    
    				startMove(this,'height',400);
    			}
    
    			oDiv1.onmouseout=function(){
    				startMove(this,'height',100);
    			}
    
    			oDiv2.onmouseover=function(){
    				startMove(this,'width',400);
    			}
    
    			oDiv2.onmouseout=function(){
    				startMove(this,'width',200);
    			}
    		}
    	}
    	function getStyle(obj,attr)
    	{
    		if(obj.currentStyle)
    		{
    			return obj.currentStyle[name];
    		}else{
    			return getComputedStyle(obj,null)[attr];
    		}
    	}
          function startMove(obj,attr,iTarget)
          {
            clearInterval(obj.timer);
            obj.timer=setInterval(function(){
            	var cur=parseInt(getStyle(obj,attr));
            	var speed=(iTarget-cur)/6;
            	speed=speed>0?Math.ceil(speed):Math.floor(speed);
            	if(cur=='iTarget')
            	{
            		clearInterval(obj.timer);
            	}
            	else{
            		obj.style[attr]=cur+speed+"px";
            	}
            },30);
    
          }
    	</script>
    </head>
    <div id="div1"></div>
    <div id="div2"></div>
    </html>


    在这里注意:
    currentStyle和getComputedStyle仅仅能用于获取页面元素的样式,不能用来设置相关值。


    假设要设置对应值,应使用style。

  • 相关阅读:
    GUID概念
    某猿的饭局
    SVN切分支步骤
    OSX:设置用户默认浏览器
    值得推荐的android开发框架简单介绍
    用实力让情怀落地!阅兵前线指挥车同款电视TCL&#160;H8800受捧
    Excel查询序列所相应的值-vLoopup函数,求比例分子改变但分母不变
    CSS3制作W3cplus的关注面板
    Spring MVC框架实例
    @property 和@synthesize
  • 原文地址:https://www.cnblogs.com/lytwajue/p/6712951.html
Copyright © 2011-2022 走看看