使用 Javascript 设置正文左边距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6405890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:33:53  来源:igfitidea点击:

Set body left margin using Javascript

javascripthtmlcss

提问by Mack

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>

回答by James Allardice

document.getElementsByTagName("body")[0].style.margin.leftshould be:

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

document.getElementsByTagName("body")[0].style.marginLeft(notice the final property).

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

回答by Abdullah Jibaly

Use:

利用:

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