首先,我们须要知道在 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{width: 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。
来源: http://www.bubuko.com/infodetail-2025754.html