刻意練習

側滑列表.list

側滑列表

04-20 :focus-within

子元素控制父元素:
子元素 focus 狀態時,會觸發父元素 :focus-within 狀態
具 focus 的元素:
<a href="#"> <button> <input> <select> <div tabindex="0">
模擬 onclick:
使用 focus 模擬 onclick 互動效果

結構

...
<section>
  <ul>
    ...
    <li>
      <div class="text">文字內容 文字內容 文字內容</div>
      <div class="icon"><a href="#"><i>❮</i></a><a href="#"><i>✎</i></a><a href="#"><i>✖</i></a></div>
    </li>
    ...
  </ul>
</section>
...

樣式


li:focus-within{
  /* 父元素: 列表項目(li) */
  transform: translateX( var(--icon-x-start) );
  background-color: var(--black-10)
}

li .icon a:focus{
  /* 子元素: 列表項目的箭頭圖示(❮) */
  background-color: var(--black-30);
  color: #fff;  
} 

程式碼

CSS list:swipe list - CodePen

語法

:focus-within - MDN
:focus - MDN
補充
- How and when to use the tabindex attribute - bitsofcode (用tabindex屬性來設定Tab鍵順序)
- 神奇的选择器 :focus-within - ChokCoco
- 详细了解CSS :focus-within伪类及其交互应用 - 张鑫旭

瀏覽器相容

:focus-within 後代焦點狀態 - CanIuse
:focus 焦點狀態 - CanIuse

comments powered by Disqus