要在默认情况下隐藏多个内容项,并在单击时显示它们,可以使用HTML、CSS和JavaScript来实现这一功能。以下是一个简单的示例,展示了如何实现这一需求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Content</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="content-container">
<button class="toggle-button">Toggle Content</button>
<div class="content-item" style="display: none;">
<h2>Content Item 1</h2>
<p>This is the first content item.</p>
</div>
<div class="content-item" style="display: none;">
<h2>Content Item 2</h2>
<p>This is the second content item.</p>
</div>
<div class="content-item" style="display: none;">
<h2>Content Item 3</h2>
<p>This is the third content item.</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
/* styles.css */
.content-container {
margin: 20px;
}
.toggle-button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.content-item {
border: 1px solid #ccc;
padding: 10px;
margin-top: 10px;
}
// script.js
document.addEventListener('DOMContentLoaded', function() {
const toggleButton = document.querySelector('.toggle-button');
const contentItems = document.querySelectorAll('.content-item');
toggleButton.addEventListener('click', function() {
contentItems.forEach(item => {
if (item.style.display === 'none' || item.style.display === '') {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
});
});
});
display: none;
,即在页面加载时默认隐藏。DOMContentLoaded
事件确保DOM完全加载后再执行脚本。通过这种方式,你可以有效地管理和展示页面上的多个内容项,提升网站的用户友好性和功能性。
领取专属 10元无门槛券
手把手带您无忧上云