简体   繁体   English

使用Javascript设置正文左边距

[英]Set body left margin using Javascript

Setting the body elements left margin using JavaScript does not work, it doesn't move 使用JavaScript设置body元素左边距不起作用,它不会移动

I don't know why this doesn't work. 我不知道为什么这不起作用。 If I set the left margin using CSS, it works, but not when I do it in JavaScript, why? 如果我使用CSS设置左边距,它可以工作,但是当我在JavaScript中使用它时,为什么呢?

<html>
<head>
    <style type="text/css">
        <!-- 
            body { margin-left: 0px; } /* set margin to anything so I can change it in JS*/
        -->
</head>
<body>

    <div id="test"  style="background-color: blue;"> blah </div>

    <script type="text/javascript">
<!--
    var APP_WIDTH = 555;
    var scrWidth  = 760; //getScreenSize()["width"];
    var xOffset   = Math.abs( Math.floor( (scrWidth/2)-(APP_WIDTH/2) ) );
    document.getElementsByTagName("body")[0].style.margin.left = xOffset + "px";  // doesn't move the div inside body?
    alert( xOffset + "px" );
    -->
</script>
</body>
</html>

document.getElementsByTagName("body")[0].style.margin.left should be: document.getElementsByTagName("body")[0].style.margin.left应该是:

document.getElementsByTagName("body")[0].style.marginLeft (notice the final property). document.getElementsByTagName("body")[0].style.marginLeft (注意最终属性)。

采用:

document.body.style.margin = "0px 0px 0px " + xOffset + "px";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM