我想做一个按钮,当它被点击,我的网页背景色改变。我已经尝试过与Javascript & Css,但没有成功!这是我的密码:
<!DOCTYPE html>
<html>
<head>
<title>
Test
</title>
<style>
.bgcolor1{
background-color:black;
}
.bgcolor2{
background-color:grey;
}
</style>
<script type="text/javascript">
</script>
</head>
<body class="bgcolor1">
<button onclick="this.className = 'bgcolor2'">Change COLOUR</button>
</body>
</html>如您所见,当用户单击按钮时,应该将类更改为"bgcolor2“,这样背景颜色将是灰色,但它只是将按钮的背景色更改为灰色&而不是文档!那么,如何用css或js更改文档的背景色,或者这段代码有什么问题呢?thx ..。
发布于 2015-10-24 09:53:27
<button onclick="document.body.className = 'bgcolor2'">Change COLOUR</button>this指的是按钮而不是身体。document.body.className = 'bgcolor2';
发布于 2015-10-24 09:56:31
只需针对document.body.className而不是this;在此场景中,this是对按钮本身的引用。使onclick属性如下所示
onclick="document.body.className='myCustomBGColor'" 其中myCustomBGColor是一个CSS类。
这是你最后的工作小提琴
.bgcolor1{
background-color:black;
}
.bgcolor2{
background-color:grey;
}<body class="bgcolor1">
<button onclick="document.body.className = 'bgcolor2'">Change COLOUR</button>
</body>
发布于 2015-10-24 09:57:40
使用document.body而不是this
<!DOCTYPE html>
<html>
<head>
<title>
Test
</title>
<style>
.bgcolor1{
background-color:black;
}
.bgcolor2{
background-color:grey;
}
</style>
<script type="text/javascript">
</script>
</head>
<body class="bgcolor1">
<button onclick="document.body.className = 'bgcolor2'">Change COLOUR</button>
</body>
</html>
https://stackoverflow.com/questions/33316777
复制相似问题