【发布时间】:2015-11-14 08:36:59
【问题描述】:
我想创建一个页面,首先显示一个红色矩形和一个按钮。如果您按下按钮,矩形将变为蓝色正方形。这是我的代码:
<!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['background-color']= "blue";那样做 -
即使我用 alert 替换函数内部的内容,它也会提醒它,所以问题出在以下代码:document.getElementById("e1").style.background-color="blue"; document.getElementById("e1").style.width = "400px"; document.getElementById("e1").style.height = "400px";
-
尝试
document.getElementById("e1").style.backgroundColor代替背景色 -
您缺少按钮的 oening 标签
标签: javascript html css