2011-06-02 141 views
1

DOM样式属性我有这样的代码在这里:如何存储在变量

function slideUp(elem,num,speed,lim){ 
    var pos = document.getElementById(elem).style.top 
    var moveUp = num 
    if(lim != pos){ 
     var int = setInterval(function(){ 
      moveUp = moveUp-100; 
      document.getElementById(elem).style.top=+moveUp+"px"; 
     },speed) 
    }else if(lim == pos){ 
     clearInterval(int); 
    } 
} 

,我有是“POS”变量未持有价值的问题。我希望它能保持我指定的元素的顶部位置

回答

2

直接从样式对象中读取并不常用,因为如果您从JavaScript设置这些值,它只会被填充。要获取从HTML或CSS设置的值,请​​使用getComputedStyle来查询元素的实际应用样式。

见这个例子来自Mozilla的文档:

function getTheStyle() { 
    var elem= document.getElementById("elem_container"); 
    var theCSSprop= window.getComputedStyle(elem,null).getPropertyValue("height"); 
    document.getElementById("output").innerHTML= theCSSprop; 
} 
+0

感谢扎克键盘上的分号键,我会尝试一下 – 2011-06-02 17:49:20

+1

或者currentStyle的Internet Explorer,看看我的代码示例。 – Halcyon 2011-06-02 17:49:34

+1

IE9之前的IE不支持getComputedStyle,你需要使用currentStyle作为Frits的例子。 IE9现在支持getComputedStyle。 – Zach 2011-06-02 17:51:29

3

我觉得你的问题是,document.getElementById(elem).style.top不具有价值,因此pos不具有价值。

您需要自己计算属性。您需要使用currentStyle/getComputedStyle,因为style.top值可以来自CSS或可以隐式定义。

来源:http://www.quirksmode.org/dom/getstyles.html

function getStyle(el,styleProp) 
{ 
    var x = document.getElementById(el); 
    if (x.currentStyle) 
     var y = x.currentStyle[styleProp]; 
    else if (window.getComputedStyle) 
     var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); 
    return y; 
} 

使用,如:

var top = getStyle(document.getElementById(elem), 'top'); 
0

有两个完全不同的问题,我在这里看到:

  1. 那 “INT” 变量声明为本地该函数的变量,这意味着一旦该函数的调用设置了一个间隔计时器,什么都不会将能够清除它,因为这个值将会丢失。我想,你可以把变量变成全局变量。
  2. 最有可能的是,您没有获得“顶级”位置,因为没有可从元素本身直接获得的样式信息。如果样式来自CSS或基本浏览器布局,那么“样式”属性不会告诉您这一点。

获得风格是一种痛苦,它在IE中与其他浏览器不同。 van Campen先生的回答描述了如何得到它。

哦,找到:-)

0
function slideUp(elem,num,speed,lim){ 
    var pos = document.getElementById(elem).style.top 
    var moveUp = num 
    if(lim != pos){ 
     var int = setInterval(function(){ 
      moveUp = moveUp-100; 
      pos += moveUp; 
      document.getElementById(elem).style.top=pos+"px"; 
     },speed) 
    } else if(lim == pos) { 
     clearInterval(int); 
    } 
}