簡體   English   中英

設置樣式不起作用?

[英]Setting style doesn't 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>

當我在var fourdocument.getElementById之間放置一個警報時,計算正確的值。 問題出在.style.marginTop = 它不會打印計算值。 為什么?

在此先感謝,Jaapyse!

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

小提琴

設置.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;

寫你的腳本如:

<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