简体   繁体   中英

Changing CSS Style Using Javascript

I am trying to change the width of a bar when I click on the button; but it's not working. I have tried copying the code, replacing the ids and rewriting the code, but I don't know why it's not working.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=8,IE=9" />
        <title>Page Title</title>
        <script type="text/javascript">
            var bar = document.getElementById("Bar");
            function load(){
                bar.style.width = "500px;";
            }
        </script>
        <link rel="stylesheet" type"text/css" href="Style.css">
    </head>
    <body>
        <div id="mainwrapper">
            Citadel goal
            <div id="Shell">
                <div id="Bar"></div>
            </div>
            <form><input type="button" value ="click" onclick="load();"/></form>
        </div>
    </body>
</html>

Two issues:

  1. You're trying to retrieve the Bar element before it exists, so your bar variable is null . Move the getElementById call into the load function, so you're not trying to get the element until after it exists.

  2. The style value shouldn't have the ; in it. Eg:

     bar.style.width = "500px;"; // Remove this ---------^ 

Working example: Live Copy

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function load() {
            var bar = document.getElementById("Bar");
            bar.style.width = "500px";
        }
    </script>
    <!-- Your stylesheet was here, replaced with this since
         we don't have your stylesheet -->
    <style>
        #Bar {
            border: 1px solid #aaa;
        }
    </style>
</head>
<body>
    <div id="mainwrapper">
        Citadel goal
        <div id="Shell">
            <!-- Note: I added something to the div as otherwise it
                 had no height; presumably your stylesheet gives it height -->
            <div id="Bar">x</div>
        </div>

        <form>
            <input type="button" value="click" onclick="load();" />
        </form>
    </div>
</body>
</html>

You function should be as this way;

function load(){
var bar = document.getElementById("Bar");
bar.style.width = "500px";
}

The reason is that initializing the property dosent know what does the "bar" contain if you does it outside the function so its better you always define it inside the fucntion.

Initialize bar Variable in to the Load Method rather than outside.

function load() {
    document.getElementById("Bar").style.width = "500px";
}

try Above Code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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