<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>读书角</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 10px;
}
button:hover {
background-color: #0056b3;
}
.hidden-content {
display: none;
margin-top: 20px;
padding: 10px;
background-color: #e9ecef;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<h1>欢迎来到我的书架</h1>
<button id="showBtn">我的</button>
<button id="changeColorBtn">改变背景颜色</button>
<div class="hidden-content" id="hiddenContent">
<p>我的</p>
</div>
</div>
<script>
const showBtn = document.getElementById('showBtn');
const hiddenContent = document.getElementById('hiddenContent');
const changeColorBtn = document.getElementById('changeColorBtn');
const container = document.querySelector('.container');
showBtn.addEventListener('click', () => {
if (hiddenContent.style.display === 'none') {
hiddenContent.style.display = 'block';
showBtn.textContent = '我的书架';
} else {
hiddenContent.style.display = 'none';
showBtn.textContent = '我的书架';
}
});
changeColorBtn.addEventListener('click', () => {
const colors = ['#f8d7da', '#d4edda', '#fff3cd', '#d1ecf1'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
container.style.backgroundColor = randomColor;
});
</script>
</body>
</html>
代码解析
HTML 部分:
定义了页面的基本结构,包括标题、两个按钮和一个初始隐藏的内容区域。
使用 class 和 id 为元素添加标识,方便后续的 CSS 样式设置和 JavaScript 操作。
CSS 部分:
设置了页面的整体样式,如字体、背景颜色、容器的宽度、内边距、边框圆角和阴影等。
对按钮和隐藏内容区域进行了样式设置,包括按钮的背景颜色、悬停效果,以及隐藏内容区域的显示和隐藏状态。
JavaScript 部分:
使用 document.getElementById 和 document.querySelector 获取页面中的元素。
为“显示隐藏内容”按钮添加了点击事件监听器,实现点击按钮时显示或隐藏内容区域,并改变按钮的文本。
为“改变背景颜色”按钮添加了点击事件监听器,实现点击按钮时随机改变容器的背景颜色。

被折叠的 条评论
为什么被折叠?



