Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/张婷/练习/案例自写/0618/案例八.html
2024-09-27 02:06:13 +08:00

174 lines
4.4 KiB
HTML
Raw 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>Document</title>
<style>
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
.title {
display: flex;
}
.title li {
margin-right: 10px;
}
.title .active {
color: red;
}
.content li {
display: none;
}
.content .active {
display: block;
}
</style>
</head>
<body>
<ul class="title"></ul>
<ul class="content"></ul>
</body>
<!-- 1 获取事件; 2 绑定事件; 3 事件处理函数。
思路:首先words里面的每一项都不是固定的,所以要考虑通过循环去加入到html中;
该事件:标题的内容: 首先,通过循环words得到里面的对象和下标,设置相关属性后,把它放到html上;
内容的内容: 同上 激活态还是通过下标实现同步-->
<script>
// 后端数据:
var words = [{
title: '首页',
content: [{
text: '首页的内容1'
},
{
text: '首页的内容2'
},
{
text: '首页的内容3'
},
{
text: '首页的内容4'
},
{
text: '首页的内容5'
},
]
},
{
title: '社会',
content: [{
text: '社会 的内容1'
},
{
text: '社会 的内容2'
},
{
text: '社会 的内容3'
},
]
},
{
title: '军事',
content: [{
text: '军事 的内容1'
},
{
text: '军事 的内容2'
},
{
text: '军事 的内容3'
},
]
},
{
title: '科技',
content: [{
text: '科技 的内容1'
},
{
text: '科技 的内容2'
},
{
text: '科技 的内容3'
},
]
}
]
//返回值
function $(className) {
return document.querySelector(className)
}
// 返回数组
function _(className) {
return document.querySelectorAll(className)
}
var title = $('.title')
var content = $('.content')
contentAll()
function titleAll() {
// 循环添加title的内容,并且判断title的class是否需要添加激活态
words.forEach((value, index) => {
title.innerHTML += `<li class="${index == 0 ? 'active':''}">${value.title}</li>`
})
// console.log(words);
var titleli = _(".title li")
var contentli = _(".content li")
// title里面的的内容也不确定,所以进行循环,并给里面的每一个对象绑定点击事件,然后同旧版样式,先清除再添加激活态
titleli.forEach((v, i) => {
v.onclick = function () {
titleli.forEach((valueli, index) => {
valueli.className = ''
contentli[index].className = ''
})
v.className = 'active'
contentli[i].className = 'active'
}
})
}
// 然后开始考虑如何插入li标签里的具体内容,同样不确定,用循环
function contentAll() {
// 同上,循环词组插入content的li标签,然后再li标签里面再循环插入li标签里面的具体文本
words.forEach((value, index) => {
content.innerHTML += `<li class="${index == 0 ? 'active':''}">${
// 这里将进行array.map(function(当前值, 下标))
// toString() 方法返回字符串。
// replaceAll()字符串替换。
value.content.map( v => { return `<p>${v.text}</p>` }).toString().replaceAll(',','')
}</li>`
})
}
titleAll()
</script>
</html>