I want to create a page that first displays a red rectangle and a button. If you press the button the rectangle will change to blue square. Here is my code:
<!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>
The problem is the rectangle doesn't change to square that means the JavaScript has some issues.
Change:
document.getElementById("e1").style.background-color= "blue";
To:
document.getElementById("e1").style.backgroundColor = "blue";
这应该工作
document.getElementById("e1").style['background-color']= "blue";
Two things -
First you have syntax error in
document.getElementById("e1").style.background-color= "blue";
It should be either
document.getElementById("e1").style['background-color']= "blue";
OR
document.getElementById("e1").style.backgroundColor= "blue";
Second, I don't know if it's a type in your question, but you missed the opening <
in your button tag. That is the reason it is failing.
What you have here is
button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
Which should be
<button type = "button" onclick = "myfunction()" style = "width: 100px ; hight: 100px ; position:center ;">Switch</button>
Here you go. There was a slight problem with your 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>
Two things.
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.