css 使用JavaScript设置正文左边距

n3schb8v  于 5个月前  发布在  Java
关注(0)|答案(3)|浏览(78)

使用JavaScript设置body元素左边距不起作用,它不移动

我不知道为什么这不起作用。如果我用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>

字符串

vc9ivgsu

vc9ivgsu1#

document.getElementsByTagName("body")[0].style.margin.left应该是:
document.getElementsByTagName("body")[0].style.marginLeft(注意最后一个属性)。

omvjsjqw

omvjsjqw2#

用途:

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

字符串

h9vpoimq

h9vpoimq3#

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>`enter code here`
    <link rel="stylesheet" href="main.css">
    <style>
        body {
            background-color: rgb(26, 42, 71);
            color: darkturquoise;
        }
    </style>
</head>
<body>
    <h1>Arrow Function</h1>
    <!-- <button onclick="click()" id="button">submit</button> -->
    <script src="mian.js"></script>
</body>
<script>
    const arrow = document.querySelector("h1")
    arrow.style.border = "2px solid red"
    arrow.style.margin = "0"
    arrow.style.padding = "0"
</script>

</html>

字符串

相关问题