问:如果让你实现下图,点击跳转后,让内容1增加一个背景颜色,你会怎么做呢?
![69693925c94eaad70f4deea454b7e994.png](https://i-blog.csdnimg.cn/blog_migrate/5fc38cdae2b00ff37e31cf1ff14fdacd.png)
可能很多小伙伴第一反应是用JS,给跳转绑定点击事件,然后用DOM获取到内容1,在给其添加css样式。如果我跟你说用css来实现,会不会一脸蒙蔽,然后想骂人。哈哈哈。其实用CSS3新增的伪类:target就能轻松搞定。
W3C是这样定义的,如下图:
![19e6ddcd674e94a2e46406ee774fe1dd.png](https://i-blog.csdnimg.cn/blog_migrate/6348aa2b60d78c0c5ccd01cad7730ada.png)
并且该伪类兼容性很好,现代浏览器都支持(ie8及以下除外)
有兴趣的小伙伴可以试试下面我写的demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
body {
background-color: #000;
}
a {
color: #fff;
font-size: 30px;
}
.one,.two,.three {
margin: 150px 0;
}
/*通过伪类:target获取点击事件*/
.one:target {
color: #fff;
font-size: 40px;
}
.two:target {
color: #CD5C5C;
font-size: 40px;
}
.three:target {
color: cadetblue;
font-size: 40px;
}
</style>
</head>
<body>
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
<div id="one" class="one">123</div>
<div id="two" class="two">456</div>
<div id="three" class="three">789</div>
</body>
</html>
补充:其实CSS3还新增了很多好用的伪类。比如,:root(选择文档的根元素),:disabled(选择每个禁用的 <input> 元素)
详见:http://www.w3school.com.cn/cssref/css_selectors.asp