標籤:his code images idt 技術 簡單 button sum ted
attr()準確的說,不應該是一個屬性,而是一個CSS的函數,我們先看看MDN上的介紹吧:
Summary
The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the style sheet. It can be used on pseudo-elements too and, in this case, the value of the attribute on the pseudo-element‘s originated element is returned.
The attr() function can be used with any CSS property, but support for properties other than content is experimental.
簡單翻譯下,英語水平有限,主要是給英語比我還差的朋友作參考,高手可以無視:
CSS函數attr()是用來擷取被選中元素的屬性值,並且在樣式檔案中使用。它也可以用在偽類元素裡,在偽類元素裡使用,它得到的是虛擬元素的原始元素的值。
attr()函數可以和任何CSS屬性一起使用,但是除了content外,其餘都還是實驗性的(簡單說就是不穩定,瀏覽器不一定支援)。
那具體怎麼用呢,給大家舉個栗子,前段時間剛好用到的,給按鈕實現提示功能,就是滑鼠放上去後,出來個小提示:
<div class="wrap"> <a href="#" class="btn" data-tip="點擊作答">一個按鈕</a></div>
.btn { display: inline-block; padding: 5px 20px; border-radius: 4px; background-color: #6495ed; color: #fff; font-size: 14px; text-decoration: none; text-align: center; position: relative;}.btn::before { content: attr(data-tip); width: 80px; padding: 5px 10px; border-radius: 4px; background-color: #000; color: #ccc; position: absolute; top: -30px; left: 50%; transform: translate(-50%); text-align: center; opacity: 0; transition: all .3s;}.btn::after { content: ‘‘; border: 8px solid transparent; border-top: 8px solid #000; position: absolute; top: -3px; left: 50%; transform: translate(-50%); opacity: 0; transition: all .3s;}.btn:hover::before { top: -40px; opacity: 1;}.btn:hover::after { top: -13px; opacity: 1;}
當然attr()還可以擷取更多的其他屬性,比如a標籤裡的href屬性等,更多的用法大家自行嘗試吧。
CSS屬性之attr()