纯css实现切换标签效果
一.首先上demo
如图所示:点击第一个按钮显示按钮样式改变,弹出第一个界面;点击第二个按钮改变按钮样式,弹出第二个界面,实现的主要方式要看我们对input的了解程度
二.实现原理
1.首先创建div,为div添加宽高,设置div为相对定位的元素
2.创建两个type为radio的input,给两个input一个相同name,让它和同级的lable绑定,注意input要display:none掉,因为input即使没有了位置,但是它的点击事件依旧存在于label内,此时的label具备了input的所有特性,且可以改变样式
3.设置label的点击事件checked
我已经默认给了第一个按钮checked
设置点击事件 使用input:checked+label
4.创建两个div,在设置相对定位的div之下(父子关系)或者和input同级关系,这两个div设置绝对定位,设置样式,然后 visibility: hidden,再通过checked让这俩个div显示
总结:想使用css来做点击事件,a与iframe当然也可以实现,但是a不能做到点击后的样式改变,另一个恢复默认样式,熟练使用input可以实现很多简单的逻辑效果,例如轮播图,一个界面内切换标签等
下面放源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=
, initial-scale=1.0">
<title>纯css实现切换标签效果</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
main {
width: 600px;
height: 600px;
background-color: violet;
}
.demo {
width: 100%;
height: 100%;
position: relative;
}
input {
display: none;
}
#check_first+label,
#check_second+label {
display: inline-block;
width: 100px;
height: 60px;
line-height: 60px;
text-align: center;
border: 1px solid;
background-color: white;
color: black;
float: left;
}
#check_second+label {
float: right;
}
#check_first:checked+label,
#check_second:checked+label {
background-color: black;
color: white;
}
.window_first,
.window_second{
position: absolute;
width: 400px;
height: 200px;
background-color: white;
top: 100px;
left: 100px;
visibility: hidden;
}
.window_second{
background-color: tomato;
}
#check_first:checked~.window_first,
#check_second:checked~.window_second{
visibility: visible;
transform: scale(1.2);
transition: all .3s ease;
}
</style>
</head>
<body>
<main>
<div class="demo">
<input type="radio" name="bt" id="check_first" checked>
<label for="check_first">按钮1</label>
<input type="radio" name="bt" id="check_second">
<label for="check_second">按钮2</label>
<div class="window_first">这是第一个界面</div>
<div class="window_second">这是第二个界面</div>
</div>
</main>
</body>
</html>