前言:今天小编发现原来a标签也可以使用伪类:focus来实现一些功能,跟大家一起分享分享,之前的文章我们用a标签的锚点功能和input,label实现tab栏切换的一些效果 今天小编就用另一种方式a标签加伪类:focus来实现这种效果,跟大家一起分享一下。还请大家多多支持哦!
在我们的印象中:focus往往配合input来使用,用来聚焦的效果,今天就用它来和a标签使用一下。
看以下的具体案例:
<!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>
</head>
<style>
a{
/* 去除a标签的默认样式 */
text-decoration: none;
/* 将a标签转换成行内块元素 */
display: inline-block;
width: 100px;
height: 50px;
text-align: center;
line-height: 50px;
border: 1px solid black;
}
div{
width: 400px;
height: 300px;
display: none;
/* 将所有的div绝对定位到一起 */
position: absolute;
}
.a{
background-color: pink;
}
.b{
background-color: green;
}
.c{
background-color:blue;
}
.d{
background-color: yellow;
}
/* a标签focus时颜色变红 */
a:focus{
color: red;
}
/* a标签focus时他下一个兄弟元素出现 */
a:nth-of-type(1):focus+.a{
display: block;
}
a:nth-of-type(2):focus+.b{
display: block;
}
a:nth-of-type(3):focus+.c{
display: block;
}
a:nth-of-type(4):focus+.d{
display: block;
}
</style>
<body>
<a href="#">标题一</a>
<div class="a"></div>
<a href="#">标题二</a>
<div class="b"></div>
<a href="#">标题三</a>
<div class="c"></div>
<a href="#">标题四</a>
<div class="d"></div>
</body>
</html>
注意:我们在选择第几个a时,只能用nth-of-type(),不能用nth-child(),因为nth-child()是父元素下面的所有孩子,而nth-of-type()是父元素下面同一类型的孩子顺序,比如上面代码中 a:nth-of-type(3)就是body下面第三个a标签,如果写成a:nth-child(3)这样就不会选中。
运行效果如下面所示:
点击标题一:
点击标题二:
点击标题三:
点击标题四:
当点击a标签的时候也会聚焦,颜色也会变,正如小编上面代码中写的一样,a在focus时变红,原来也会实现。
这样也会实现一种tab栏切换的效果,今天小编刚刚发现的这种写法,在很多页面中的这种切换效果用这种方法去实现是不是很简单呢。大家快去试一试吧。