css点击改变背景颜色

2023-12-24 17:30:09 举报文章

CSS可以用来改变网页的样式,包括字体、颜色、大小等。其中,改变背景颜色也是常用的一种方式。以下是使用CSS来控制点击改变背景颜色的示例:

<!DOCTYPE html>
<html>
<head>
  
  
   
<title>点击改变背景颜色</title>
  
  
   
<style>
  
  
   
  
  
   
body {
  
  
   
  
  
   
  
  
   
background-color: #eee;
  
  
   
  
  
   
}
  
  
   
  
  
   
button {
  
  
   
  
  
   
  
  
   
background-color: #4CAF50;
 /*绿色*/
  
  
   
  
  
   
  
  
   
border: none;
  
  
   
  
  
   
  
  
   
color: white;
  
  
   
  
  
   
  
  
   
padding: 15px 32px;
  
  
   
  
  
   
  
  
   
text-align: center;
  
  
   
  
  
   
  
  
   
text-decoration: none;
  
  
   
  
  
   
  
  
   
display: inline-block;
  
  
   
  
  
   
  
  
   
font-size: 16px;
  
  
   
  
  
   
  
  
   
margin: 4px 2px;
  
  
   
  
  
   
  
  
   
cursor: pointer;
  
  
   
  
  
   
  
  
   
border-radius: 5px;
  
  
   
  
  
   
  
  
   
transition: background-color 0.5s ease;
 /*过渡效果*/
  
  
   
  
  
   
}
  
  
   
  
  
   
button:hover {
  
  
   
  
  
   
  
  
   
background-color: #3e8e41;
 /*深绿*/
  
  
   
  
  
   
}
  
  
   
</style>
</head>
<body>
  
  
   
<button onclick="changeColor()">点击我改变背景颜色</button>
  
  
   
<script>
  
  
   
  
  
   
function changeColor() {
  
  
   
  
  
   
  
  
   
document.body.style.backgroundColor = "#f0f";
 /*紫色*/
  
  
   
  
  
   
}
  
  
   
</script>
</body>
</html> 

这个示例中,我们使用了一个按钮元素和一个JavaScript函数来实现通过点击按钮改变背景颜色的效果。CSS部分中定义了按钮的样式和过渡效果,当鼠标悬停在按钮上时,背景颜色会从绿色过渡到深绿色。JavaScript部分中定义了一个函数,当按钮被点击时,可以通过修改body元素的style属性来改变背景颜色。通过CSS和JavaScript的配合,我们可以轻松地实现点击改变背景颜色的效果。

如果你认为本文可读性较差,内容错误,或者文章排版错乱,请点击举报文章按钮,我们会立即处理!