3

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

<!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 four,它document.getElementById会计算正确的值。问题出在.style.marginTop =. 它不打印计算值。为什么?

在此先感谢,Jaapyse!

4

3 回答 3

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

小提琴

于 2013-07-15T08:01:31.400 回答
5

当你设置 .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;
于 2013-07-15T08:04:23.743 回答
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>
于 2013-07-15T08:07:30.850 回答