css左侧列表和右侧显示效果代码
我的站长站
2024-08-07
共人阅读
使用 CSS + HTML 实现左侧导航列表、右侧内容展示经典左右布局,采用 Flex 弹性布局实现自适应,结构简洁、兼容性好。左侧固定 / 自适应宽度菜单,右侧填充剩余区域展示内容,附带基础样式、hover 交互,可用于后台管理、文档页面、商城分类等场景。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>左侧列表和右侧功能显示</title>
<style>
.container {
display: flex;
width: 1175px;
height: calc(100vh - 10px); /* 设置内容区域高度为视口高度减去10px */
border: 1px solid #ccc;
overflow: hidden;
}
.sidebar {
flex: 1;
background-color: #f0f0f0;
padding: 20px;
border-right: 1px solid #ccc;
overflow-y: auto;
}
.main-content {
flex: 3;
padding: 20px;
overflow-y: auto; /* 如果内容过多,可以允许内容区域滚动 */
}
.sidebar ul {
list-style-type: none;
padding: 0;
}
.sidebar li {
margin-bottom: 10px;
cursor: pointer;
}
.sidebar li:hover {
color: #007bff;
}
.selected {
color: #007bff;
font-weight: bold;
}
</style>
</head>
<body>
<div>
<div>
<ul>
<li onclick="showContent('option1')">地理</li>
<li onclick="showContent('option2')">化学</li>
<li onclick="showContent('option3')">历史</li>
<li onclick="showContent('option4')">生物</li>
<li onclick="showContent('option5')">数学</li>
<li onclick="showContent('option6')">物理</li>
<li onclick="showContent('option7')">音乐</li>
<li onclick="showContent('option8')">英语</li>
<li onclick="showContent('option9')">语文</li>
<li onclick="showContent('option10')">政治</li>
<!-- 添加更多选项 -->
</ul>
</div>
<div id="mainContent">
<h>请选择</h>
</div>
</div>
<script>
function showContent(option) {
// 清除所有选项的样式
var lis = document.querySelectorAll('.sidebar li');
lis.forEach(li => {-
li.classList.remove('selected');
});
// 添加选中选项的样式
var selectedLi = document.querySelector(`.sidebar li:nth-child(${option.slice(-1)})`);
selectedLi.classList.add('selected');
// 根据选项显示对应的内容
var mainContent = document.getElementById('mainContent');
mainContent.innerHTML = getOptionContent(option);
}
function getOptionContent(option) {
switch(option) {
case 'option1':
return '<iframe src="地理" width="100%" height="600px"></iframe>';
case 'option2':
return '<iframe src="化学" width="100%" height="600px"></iframe>';
case 'option3':
return '<iframe src="历史" width="100%" height="600px"></iframe>';
case 'option4':
return '<iframe src="生物" width="100%" height="600px"></iframe>';
case 'option5':
return '<iframe src="数学" width="100%" height="600px"></iframe>';
case 'option6':
return '<iframe src="物理" width="100%" height="600px"></iframe>';
case 'option7':
return '<iframe src="音乐" width="100%" height="600px"></iframe>';
case 'option8':
return '<iframe src="英语" width="100%" height="600px"></iframe>';
case 'option9':
return '<iframe src="语文" width="100%" height="600px"></iframe>';
case 'option10':
return '<iframe src="政治" width="100%" height="600px"></iframe>';
}
}
</script>
</body>
</html>