原生js
<!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>
div {
width:200px;
height:200px;
backgroundcolor:pink;
display: none;
}
.p {
background-color: pink
}
.b {
display: block;
}
</style>
</head>
<body>
<button class="p">标题一</button>
<button>标题二</button>
<button>标题三</button>
<div class="b">内容一</div>
<div>内容二</div>
<div>内容三</div>
<script>
var oul = document.querySelectorAll('button')
var ool = document.querySelectorAll('div')
var num = 0;
for (var i = 0; i < oul.length; i++) {
oul[i].index = i;
oul[i].onclick = function () {
for (var i = 0; i < oul.length; i++) {
oul[i].className = ''
ool[i].className = ''
}
this.className = 'p'
ool[this.index].className = 'b'
num = this.index;
}
}
// 设置一个定时器,用于切换标题样式,同步内容
setInterval(function () {
num++;
num %= 3;
for (var i = 0; i < oul.length; i++) {
oul[i].className = ''
ool[i].className = ''
}
oul[num].className = 'p'
ool[num].className = 'b'
}, 2000)
</script>
</body>
</html>
React选项卡切换
在views中创建index.tsx 和index.less,less用于写样式,tsx用于写相关功能和渲染的页面内容,
在tsx中引入less文件,在src>routes中的index中引入index.tsx
使用map()方法对标题进行循环,这边相当于for循环,需要注意的是在使用map()循环的时候,需要写key值,不然会出现报错
index.tsx
import { Component } from "react";
import './index.less'
interface iProps { }
interface iState { tabindex: number } // 检测tabindex的值符不符合number类型
interface iTabbtn {
id: string,
con: string,
}
// 检测按钮和文字相关的属性是否符合要求
interface iTabList {
id: string;
text: string;
}
export default class Tab extends Component<iProps, iState> {
tabbtn: iTabbtn[] = [];
tabList: iTabList[] = []
constructor(props: iProps) {
super(props);
this.tabbtn = [
{
id: '按钮一',
con: '内容一'
},
{
id: '按钮二',
con: '内容二'
},
{
id: '按钮三',
con: '内容三'
}
]
this.tabList = [
{
id: 'con1',
text: '内容一'
},
{
id: 'con2',
text: '内容二'
},
{
id: 'con3',
text: '内容三'
}
]
this.state = { tabindex: 0 }
}
dianji(index: number) {
this.setState({ tabindex: index })
}
render() {
const tabindex = this.state.tabindex;
return (
<div className='tab'>
{this.tabbtn.map((item, index) => <button className={index === tabindex ? 'a' : ''} key={item.id} onClick={this.dianji.bind(this, index)}>{item.con}</button>)}
{this.tabList.map((item, index) => <div className={index === tabindex ? 'c' : ''} key={item.id}>{item.text}</div>)}
</div>)
}
}
index.less
.tab{
.a{
background-color: red;
}
div{
width: 100px;
height: 30px;
display: none;
}
.c{
display: block;
}
}