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。

  • 相关阅读:
    SQL Server中的Merge关键字
    详解公用表表达式(CTE)
    SQL Server优化50法
    Chrome下的脚本管理器
    初步设计了一下视频工具合集的界面
    迅雷的剪贴板冲突好强大
    在C#中用MediaInfo获取视频或音频的属性
    用Command模式简单的实现Undo&Redo功能
    用DoddleReport快速生成报表
    移动支付时代早日来临吧
  • 原文地址:https://www.cnblogs.com/lytwajue/p/6712951.html
Copyright © 2011-2022 走看看