V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
waiaan
V2EX  ›  CSS

问一个 css 选择器的问题

  •  
  •   waiaan · 2020-03-16 17:03:31 +08:00 · 1703 次点击
    这是一个创建于 1473 天前的主题,其中的信息可能已经有所发展或是发生改变。
    <div>
      <div class="item"></div>
      <div class="item selected"></div>
      <div class="item selected"></div>
      <div class="item"></div>
      <div class="item selected"></div>
      <div class="item"></div>
    </div>
    

    如何选中第一个带‘selected’类名的元素?

    12 条回复    2020-07-08 10:14:47 +08:00
    SunriseFox
        1
    SunriseFox  
       2020-03-16 17:19:08 +08:00
    CSS 八成大概也许可能差不多做不到...
    cmdOptionKana
        2
    cmdOptionKana  
       2020-03-16 17:20:17 +08:00
    实在不行就加上 js 吧
    waiaan
        3
    waiaan  
    OP
       2020-03-16 17:26:55 +08:00
    @cmdOptionKana 只能如此了。
    rioshikelong121
        4
    rioshikelong121  
       2020-03-16 17:29:26 +08:00
    应该做不了 因为那一堆 nth-of-type 等选择器只适用于 element 而不是 class。
    Carseason
        5
    Carseason  
       2020-03-16 17:33:14 +08:00
    .item.selected:last-child
    FragmentLs
        6
    FragmentLs  
       2020-03-16 17:33:29 +08:00   ❤️ 1
    ```css
    // first .selected rules
    .item.selected {
    }

    // rest of the .selected rules
    .item.selected ~ .item.selected {
    }
    ```
    Carseason
        7
    Carseason  
       2020-03-16 17:33:57 +08:00
    打错了
    MinYa
        8
    MinYa  
       2020-03-16 17:34:32 +08:00   ❤️ 1
    举例默认背景颜色黑色,选中要设置为白色。
    .selected{
    background: #fff;
    }
    .selected ~ .selected{
    background: #000;
    }
    waiaan
        9
    waiaan  
    OP
       2020-03-16 17:35:12 +08:00
    @FragmentLs
    @MinYa

    可行,多谢!
    loading
        10
    loading  
       2020-03-16 18:50:59 +08:00 via Android
    这种问题,我会用 chrome,控制台,copy selecter……
    ChanKc
        11
    ChanKc  
       2020-07-08 10:10:19 +08:00 via Android
    div .item.selected::first-child
    ChanKc
        12
    ChanKc  
       2020-07-08 10:14:47 +08:00 via Android
    为什么我感觉前面的答案都是“选择 selected 且不是第一个”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3924 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:28 · PVG 18:28 · LAX 03:28 · JFK 06:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.