设置样式不起作用?

时间:2013-07-15 07:58:50

标签: javascript css

为什么这个脚本不起作用?

<!DOCTYPE html>
<html>

    <head>
        <title>Hello StackOverflow!</title>
    </head>

    <body>
        <div id="testing">
            <p>Bladybla</p>
        </div>
        <script>
            var one = window.innerWidth;
            var two = 5;
            var three = one / two;
            var four = '"' + Math.round(three) + "px" + '"';
            document.getElementById("testing").style.marginTop = four;
        </script>
    </body>

</html>

当我在var fourdocument.getElementById之间发出提醒时,会计算出正确的值。问题出在.style.marginTop =。它不会打印计算值。为什么?

提前致谢,Jaapyse!

3 个答案:

答案 0 :(得分:8)

var four = Math.round(three) + "px";

Fiddle

答案 1 :(得分:4)

设置.style.marginTop时,不需要在值中包含引号。

如果您将其设置为硬编码值,则可能有:

document.getElementById("testing").style.marginTop = "5px";

但是,您可以有效地将其设置为:

document.getElementById("testing").style.marginTop = '"5px"';

这是一个无效的值,因此会被忽略。

将您的代码更改为:

var one = window.innerWidth;
var two = 5;
var three = one / two;
var four = Math.round(three) + 'px';
document.getElementById("testing").style.marginTop = four;

答案 2 :(得分:0)

写下你的脚本:

<script>
                var one = window.innerWidth;
                var two = 5;
                var three = one / two;
                var four = Math.round(three);
                document.getElementById("testing").style.marginTop = four + 'px';
            </script>