使用 CSS 的 :before 和 :after 選取器做一個箭頭樣式

來源:互聯網
上載者:User

標籤:

對於 :before 和 :after 選取器,大家並不陌生,但是很少有人會主動去用它們。先解釋下它們的定義和用法:

:before 選取器在被選元素的內容前面插入內容,:after 選取器在被選元素的內容後面插入內容,都會使用 content 屬性來指定要插入的內容。

有時候,項目中或多或少需要一些箭頭,如果用圖片來做,感覺就有點 low 了,而上面這兩個選取器是最好的選擇。效果如下:

html 代碼如下:

<div class="test"></div>

 

css 代碼如下:

.test {    position: relative;    width: 120px;    height: 40px;    border: 1px solid #d2d2d2;    border-radius: 3px;}.test:after {    position: absolute;    right: 15px;    top: 18px;    width: 0;    height: 0;    content: "";    border-width: 6px 6px 0 6px;    border-style: solid;    border-color: #fff transparent;    -webkit-transition: all .25s;       -moz-transition: all .25s;        -ms-transition: all .25s;         -o-transition: all .25s;            transition: all .25s;}.test:before {    position: absolute;    right: 13px;    top: 18px;    width: 0;    height: 0;    content: "";    border-width: 8px 8px 0 8px;    border-style: solid;    border-color: #d36969 transparent;    -webkit-transition: transform .25s;       -moz-transition: transform .25s;        -ms-transition: transform .25s;         -o-transition: transform .25s;            transition: transform .25s;}.test.active:after{           top: 20px;    -webkit-transform: rotate(180deg);       -moz-transform: rotate(180deg);        -ms-transform: rotate(180deg);         -o-transform: rotate(180deg);            transform: rotate(180deg); }.test.active:before{    -webkit-transform: rotate(180deg);       -moz-transform: rotate(180deg);        -ms-transform: rotate(180deg);         -o-transform: rotate(180deg);            transform: rotate(180deg);        }

通過 :before 和 :after 兩個虛擬元素,設定 content 為空白,寬高為零,邊框和顏色,產生兩個個等邊三角形,一個是紅色的三角,其邊長稍大,一個是白色的三角。會有人問為什麼白色三角是通過 :after 產生的,因為 :after 產生的白色三角才能覆蓋在 :before 產生的紅色三角,而形成一個箭頭(一定要設定好定位的 top 值,使兩個三角的底邊重合)。

 

js 代碼如下:

$(‘.test‘).on(‘click‘,function(){      $(this).toggleClass(‘active‘);})

點擊的時候箭頭會旋轉180度,效果如下:

 

使用 CSS 的 :before 和 :after 選取器做一個箭頭樣式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.