简体   繁体   English

设置样式不起作用?

[英]Setting style doesn't work?

Why does this script not work? 为什么这个脚本不起作用?

<!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>

When I place an alert between var four and the document.getElementById is calculates the right value. 当我在var fourdocument.getElementById之间放置一个警报时,计算正确的值。 The problem is in the .style.marginTop = . 问题出在.style.marginTop = It doesn't print the calculated value. 它不会打印计算值。 WHY? 为什么?

Thanks in advance, Jaapyse! 在此先感谢,Jaapyse!

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

小提琴

When you set .style.marginTop, you don't need to include quotes in your value. 设置.style.marginTop时,不需要在值中包含引号。

If you were setting it to a hardcoded value, you might have: 如果您将其设置为硬编码值,则可能具有:

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

However, you're effectively setting it to something like: 但是,您有效地将其设置为:

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

This is then an invalid value, so it gets ignored. 这是一个无效值,因此会被忽略。

Change your code to this: 将您的代码更改为:

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

write your script like : 写你的脚本如:

<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>

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

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