Files
2024-09-27 02:06:13 +08:00

145 lines
3.4 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>tabs切换</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
ul {
display: flex;
}
.tabs_title {
height: 45px;
align-items: center;
}
.tabs_title li {
margin: 0 10px;
}
.tabs_content li {
display: none;
}
.active_content {
display: block !important;
}
.active_title {
color: red;
}
</style>
</head>
<body>
<ul class="tabs_title"></ul>
<ul class="tabs_content">
</ul>
</body>
<script>
var index = 0;
var tabsData = [
{
id: 1,
title: '首页',
page: 1,
content: [
{ text: '首页的内容1' },
{ text: '首页的内容2' },
{ text: '首页的内容3' },
]
},
{
id: 2,
title: '社会',
page: 1,
content: [
{ text: '社会的内容1' },
{ text: '社会的内容2' }
]
},
{
id: 3,
title: '财经',
page: 1,
content: [
{ text: '财经的内容1' },
{ text: '财经的内容2' },
{ text: '财经的内容3' },
{ text: '财经的内容4' },
]
},
];
// 渲染 tabs标题的li标签
function renderTitle() {
tabsData.forEach((v, i) => {
$(".tabs_title").innerHTML += `<li class="${i == 0 ? 'active_title' : ''}">${v.title}</li>`;
$(".tabs_content").innerHTML += `<li class="${i == 0 ? 'active_content' : ''}"></li>`;
})
_(".tabs_title li").forEach((v,i) => {
v.onclick = () => {
// 保存你点击的li标签的下标方便下面 renderContent 使用
index = i;
// 当你点击li的时候先删除所有li标签上的类名
_(".tabs_title li").forEach((j, idx) => {
j.classList.remove("active_title")
_(".tabs_content li")[idx].classList.remove("active_content");
});
// 然后再为你点击的那个li标签加激活样式的类名
v.classList.add("active_title");
_(".tabs_content li")[i].classList.add("ative_content");
renderContent();
}
})
}
// 渲染和标题对应的内容content
function renderContent() {
// 访问到你点击的标题所对应的内容的li
_(".tabs_content li")[index].innerHTML = ""
tabsData[index].content.forEach(v => {
_(".tabs_content li")[index].innerHTML += `<p>${v.text}</p>`
})
}
renderTitle();
renderContent();
// 封装的方法用来获取所有li标签的数组
function _(className) {
return document.querySelectorAll(className)
}
function $(className) {
return document.querySelector(className)
}
</script>
</html>