How do I set the margin of an object in IE?

后端 未结 3 1329
北海茫月
北海茫月 2020-12-29 03:59

I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn\'t work in Internet Explorer.

Here is the J

相关标签:
3条回答
  • 2020-12-29 04:27

    First of all, you should really use a javascript library like jQuery or Dojo. I also recommend www.debugbar.com for inspecting IE's DOM.

    About your problem, elem.style = "margin: 10px" should work in IE.

    Hope this helps!

    0 讨论(0)
  • 2020-12-29 04:30

    [Updated in 2016] On all current browsers (including IE8+), your code

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

    works fine.

    On very old IE (< 8) versions, you must use this non-standard contraption instead:

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

    EDIT - From deleted comment by OP:

    Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..)

    0 讨论(0)
  • 2020-12-29 04:39

    Your code works in IE8 for me.

    <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>
    

    In IE6, it appears to be working as well after a very short pause.

    0 讨论(0)
提交回复
热议问题