IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Trick:CSS3的:target实现选项卡切换

    dwqs发表于 2015-05-20 00:18:42
    love 0

    :target是什么?

    MDN是这样描述的::target

    The :target pseudo-class represents the unique element, if any, with an id matching the fragment identifier of the URI of the document.

    在document中,可以设置锚链接,举个粟子:

    1. href="#tab">Test :target
    2. href="#tab2">Test 2:target
    3. id="tab">This is a tab.
    4. id="tab2">This is another tab.

    上面存在两个锚链接:#tab和t#ab2。当点击锚链接时,就会跳到对应的div,则::target就是给这些div用的。添加一下CSS

    1. :target{
    2. color:red;
    3. }
    4. #tab:target::after{
    5. content:"tab1"
    6. }

    点击锚链接,对应链接的div的文本变成红色,另外,给#tab后面插入一个文本。(ps:关于content属性用法:CSS3的content属性详解)
    效果猛戳:https://jsfiddle.net/dwqs/cL8rawov/
    应该大致明白了:target的含义了吧,如果不知道用,看看这篇文章:Using the :target selector

    :target可以做什么

    最简单的用处:利用:target实现选项卡切换。
    HTML:

    1. class="tab-control">
    2. href="#tab1">tab1
    3. href="#tab2">tab2
    4. href="#tab3">tab3
    5. class="tabs">
    6. id="tab1" class="tab">This is a tab1
    7. id="tab2" class="tab">This is a tab2
    8. id="tab3" class="tab">This is a tab3

    CSS:

    1. .tab-control a{
    2. display:inline-block;
    3. text-decoration:none;
    4. color:#FFF;
    5. height:20px;
    6. width:40px;
    7. text-align:center;
    8. line-height:20px;
    9. background:rgba(70,121,189,0.75);
    10. }
    11. .tab-control a:hover{
    12. background:rgba(70,121,189,1);
    13. }
    14. .tabs{
    15. position:relative;
    16. border:1px solid red;
    17. height:200px;
    18. width:135px;
    19. overflow:hidden;
    20. }
    21. .tab{
    22. height:100%;
    23. width:100%;
    24. }
    25. :target{
    26. display:block;
    27. }

    看看效果:Demo
    当然,:target的功能不仅局限于此。隐藏元素、创建lightbox 等。MDN上给了很多个demo:more demo.
    你自己也可以脑洞大开一下,哈哈。

    浏览器支持

    对于:target伪类,浏览器支持情况还是不错的。
    :target
    具体可以戳::target

    淡忘~浅思猜你喜欢

    【译】下一代选择器:CSS4

    CSS3的content属性详解

    CSS3模拟侧滑菜单

    【译】CSS中的变量使用详解

    CSS3实现导航
    无觅

    转载请注明:淡忘~浅思 » Trick:CSS3的:target实现选项卡切换



沪ICP备19023445号-2号
友情链接