2008-11-25 56 views
25

我想从JavaScript设置对象的边距。我可以在Opera & Firefox中执行此操作,但代码在Internet Explorer中无法使用。如何在IE中设置对象的边距?

这里是JavaScript,我有:

function SetTopMargin (ObjectID, Value) 
{ 
    document.getElementById(ObjectID).style.marginTop = Value.toString() + "px"; 
} 

,它被称为是这样的:

SetTopMargin("test_div_id", 100); 

因此,没有人知道一些代码,将在Internet Explorer中工作吗?

+0

我刚刚在IE7中试过你的代码,它工作正常... – 2008-11-25 17:22:15

+0

奇怪,我只是试过底部提供的示例,它使用我的代码,它的工作....非常困惑:s – Cheetah 2008-11-25 18:05:41

回答

30

[2016年更新]在目前所有的浏览器(包括IE8 +),你的代码

document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px'; 

工作正常。

很老 IE(< 8)版本,则必须使用此非标准玩意儿来代替:

document.getElementById(ObjectId).style.setAttribute(
    'marginTop', Value.ToString() + 'px'); 

编辑 - 由OP从删除评论:

注虽然您可以在当前IE中使用style.setAttribute('margin-top',..),但8岁以上需要style.setAttribute('marginTop',..)

-2

首先,你应该真的使用像jQuery或Dojo这样的JavaScript库。我还建议www.debugbar.com检查IE的DOM。

关于您的问题,elem.style = "margin: 10px"应该在IE中工作。

希望这会有所帮助!

+0

我没有使用的原因一个图书馆是它的定制。专为小规模工作而设计。我正在创建自己的轻量级灯箱版本 – Cheetah 2008-11-25 17:49:14

4

您的代码适用于IE8。

<html> 
    <head> 
    <script type="text/javascript"> 
    function SetTopMargin (ObjectID, Value) 
    { 
     document.getElementById(ObjectID).style.marginTop = Value.toString() + "px"; 
    } 
    </script> 
</head> 
<body> 
    <button id="btnTest" onclick="SetTopMargin('btnTest', 100);">Test</button> 
</body> 
</html> 

在IE6中,它在暂停后非常短暂地工作。