如何在IE中设置对象的边距?

Che*_*tah 26 javascript css internet-explorer

我试图从JavaScript设置对象的边距.我可以在Opera和Firefox中执行此操作,但代码在Internet Explorer中不起作用.

这是我的JavaScript:

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

它被称为这样:

SetTopMargin("test_div_id", 100);
Run Code Online (Sandbox Code Playgroud)

那么有谁知道一些可以在Internet Explorer中运行的代码?

phi*_*hag 34

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

document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px';
Run Code Online (Sandbox Code Playgroud)

工作良好.

非常旧的 IE(<8)版本中,您必须使用此非标准装置:

document.getElementById(ObjectId).style.setAttribute(
   'marginTop', Value.ToString() + 'px');
Run Code Online (Sandbox Code Playgroud)

编辑 - 来自OP删除的评论:

请注意,虽然您可以在当前IE中使用style.setAttribute('margin-top',..),但8及更早版本需要style.setAttribute('marginTop',..)