【问题标题】:How do I set the margin of an object in IE?如何在 IE 中设置对象的边距?
【发布时间】:2010-09-24 00:10:14
【问题描述】:

我正在尝试通过 JavaScript 设置对象的边距。我可以在 Opera 和 Firefox 中执行此操作,但代码在 Internet Explorer 中不起作用。

这是我的 JavaScript:

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

它是这样称呼的:

SetTopMargin("test_div_id", 100);

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

【问题讨论】:

  • 我刚刚在 IE7 中尝试了您的代码,它运行良好...
  • 很奇怪,我刚刚尝试了底部提供的示例,它使用了我的代码并且它可以工作....非常困惑:s

标签: javascript css internet-explorer


【解决方案1】:

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

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

工作正常。

非常旧的 IE (

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

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

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

【讨论】:

    【解决方案2】:

    您的代码适用于我的 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 中,它似乎在很短的暂停后也能正常工作。

    【讨论】:

      【解决方案3】:

      首先,您应该真正使用 jQuery 或 Dojo 之类的 javascript 库。我还推荐使用 www.debugbar.com 来检查 IE 的 DOM。

      关于您的问题,elem.style = "margin: 10px" 应该可以在 IE 中使用。

      希望这会有所帮助!

      【讨论】:

      • 我不使用图书馆的原因是它是定制的。体积小,适合特定工作。我正在创建自己的轻量级灯箱
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2022-10-21
      • 2011-06-03
      • 2012-09-16
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多