简体   繁体   English

使用Javascript更改CSS样式

[英]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. 我试过复制代码,替换ID并重写代码,但我不知道为什么它不起作用。

<!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 . 您尝试在Bar元素存在之前检索它,因此bar变量为null Move the getElementById call into the load function, so you're not trying to get the element until after it exists. getElementById调用移动 load函数中,因此在它存在之前,您不会尝试获取该元素。

  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. 原因是初始化属性dosent知道"bar"包含什么,如果你在函数之外执行它,所以你总是在函数内定义它更好。

Initialize bar Variable in to the Load Method rather than outside. 初始化栏变量到加载方法而不是外部。

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

try Above Code. 尝试以上代码。

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

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