繁体   English   中英

无法使用 JavaScript 更改 CSS

[英]Can't change CSS with JavaScript

我想创建一个页面,首先显示一个红色矩形和一个按钮。 如果您按下按钮,矩形将变为蓝色方块。 这是我的代码:

<!doctype html>
<html>
<head>



    <style>
        #e1 {
            background-color: red ;
            width: 400px ;
            height: 200px ;
            margin: 0 auto;

        }
        .wrapper {
            text-align: center;
        }

    </style>


</head>

<body>


    <div id ="e1">
    </div>



    <div class="wrapper">
    <button type="button" onclick="myfunction()" style="width: 100px; height: 100px; position:center;">Switch</button>
    </div>

    <script type="text/javascript">
        function myfunction() {
            document.getElementById("e1").style.background-color= "blue";
            document.getElementById("e1").style.width = "400px";
            document.getElementById("e1").style.height = "400px";
        }
    </script>
</body>
</html>

问题是矩形没有变成正方形,这意味着 JavaScript 有一些问题。

改变:

document.getElementById("e1").style.background-color= "blue";

到:

document.getElementById("e1").style.backgroundColor = "blue";

这应该工作

 document.getElementById("e1").style['background-color']= "blue";

两件事情 -

首先你有语法错误

document.getElementById("e1").style.background-color= "blue";

它应该是

document.getElementById("e1").style['background-color']= "blue";

或者

document.getElementById("e1").style.backgroundColor= "blue";

其次,我不知道它是否是您问题中的一种类型,但是您错过了按钮标签中的开头< 这就是它失败的原因。

你在这里拥有的是

button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>

哪个应该是

<button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>

工作小提琴

干得好。 你的 HTML 有一个小问题

<!doctype html>
<html>
<head>



    <style>
        #e1 {
            background-color: red ;
            width: 400px ;
            height: 200px ;
            margin: 0 auto;

        }
        .wrapper {
            text-align: center;
        }

    </style>


</head>

<body>


    <div id ="e1">
    </div>



    <div class="wrapper">
    <button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
    </div>

    <script type="text/javascript">
        function myfunction() {
            document.getElementById("e1").style.backgroundColor= "blue";
            document.getElementById("e1").style.width = "400px";
            document.getElementById("e1").style.height = "400px";
        }
    </script>
</body>
</html>

两件事情。

  1. 完成您的按钮标签。 它缺少“按钮”之前的初始“<”。
  2. 在 JavaScript 单击处理程序中将 background-color 更改为 backgroundColor。

暂无
暂无

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

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