利用 :placeholder-shown 选择器实现 label 浮动效果
設(shè)計(jì)師似乎喜歡用?浮動(dòng) label 模式?來設(shè)計(jì)華麗的效果,雖然我不確定我是否百分百喜歡這種方式,但我忍不住快速實(shí)現(xiàn)了一個(gè)這樣的 demo。這個(gè)版本用上了一些我最近才看見的現(xiàn)代 CSS 表單樣式技巧,特別是?:placeholder-shown?選擇器。
先說重點(diǎn):不管從形狀或者形式上,這都不是一種最佳實(shí)踐。這個(gè) demo 的實(shí)現(xiàn)適用于某些瀏覽器的較新版本 - 尤其是 Chrome/Opera 和 Safari/WebKit。但它在 Firefox 上運(yùn)行得一塌糊涂。要注意了,我可幾乎沒有測(cè)試過它。
我主要是參考了下面這些技巧來實(shí)現(xiàn)該效果的:
最后一點(diǎn)正是將我這個(gè)實(shí)現(xiàn)與?Chris Coyier?和?Jonathan Snook?的示例區(qū)分開來的地方,后兩者均使用了?:valid?偽類。我認(rèn)爲(wèi)我這個(gè) demo 背后有特定的局限性,但正如我一開始所講,對(duì)于瀏覽器支持總是會(huì)有限制的。
譯注::placeholder-shown?屬于尚未發(fā)行的 CSS4 規(guī)范,查詢?Can I Use?可以得知,迄今為止只有 Chrome (>=47)、Safari (>=9)、Opera (>=35)、Android Browser (>=47) 和 Chrome for Android (>=47) 這五種瀏覽器支持?:placeholder-shown?偽類。作者在這里提及的局限性應(yīng)該就是指瀏覽器對(duì)?:placeholder-shown?的支持度。
這個(gè)版本改用了?:placeholder-shown?偽類,但不僅僅是在 placeholder 文本不顯示時(shí)移動(dòng) label 的位置 - 在該模型預(yù)設(shè)的工作方式中?:placeholder-shown?偽類發(fā)揮著很好的作用。
這里是相關(guān) HTML 代碼:
<div class="field"><input type="text" placeholder="Jane Appleseed"><label for="fullname">Name</label> </div>...以及 CSS 代碼:
/** * 把區(qū)域設(shè)置為 flex 容器,并逆序排列,使得 label 標(biāo)簽顯示在上方 */ .field {display: flex;flex-flow: column-reverse; } /** * 給 label 和 input 設(shè)置一個(gè)過渡屬性 */ label, input {transition: all 0.2s; }input {font-size: 1.5em;border: 0;border-bottom: 1px solid #ccc; } /** * 設(shè)置 input 獲得焦點(diǎn)時(shí)的邊框樣式 */ input:focus {outline: 0;border-bottom: 1px solid #666; } /** * 1\. 標(biāo)簽應(yīng)保持在一行內(nèi),并最多占據(jù)字段 2/3 的長度,以確保其比例合適且不會(huì)出現(xiàn)換行。 * 2\. 修正光標(biāo)形狀,使用戶知道這里可以輸入. * 3\. 把標(biāo)簽往下平移并放大1.5倍,使其覆蓋 placeholder 層. */ label {/* [1] */max-width: 66.66%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;/* |2] */cursor: text;/* [3 */transform-origin: left bottom; transform: translate(0, 2.125rem) scale(1.5); } /** * 默認(rèn)情況下,placeholder 應(yīng)該是透明的,并且應(yīng)該繼承 transition 屬性。 */ ::-webkit-input-placeholder {transition: inherit;opacity: 0; } /** * 在 input 獲得焦點(diǎn)時(shí),顯示 placeholder 內(nèi)容。 */ input:focus::-webkit-input-placeholder {opacity: 1; } /** * 1\. 當(dāng)元素獲取焦點(diǎn)時(shí),還原 transform 效果,把 label 移回原來的位置。 * 并且,當(dāng) placeholder 不顯示,比如用戶已經(jīng)輸入了內(nèi)容時(shí),也作同樣處理。 * 2\. ...并把光標(biāo)設(shè)置為指針形狀。 */ input:not(:placeholder-shown) + label, input:focus + label {transform: translate(0, 0) scale(1); /* [1] */cursor: pointer; /* [2] */ }2016-01-26 更新: 我更新了 label 的選擇器,以便其對(duì)應(yīng)的 input 標(biāo)簽擁有 :placeholder-shown 偽類時(shí),才使用 label 的 transform 效果。那樣的話,不支持的瀏覽器就回退到 “正常模式” ,也就是標(biāo)簽顯示在 input 上方。
原文發(fā)布時(shí)間為:2016年04月20日
本文來自云棲社區(qū)合作伙伴掘金,了解相關(guān)信息可以關(guān)注掘金網(wǎng)站。
總結(jié)
以上是生活随笔為你收集整理的利用 :placeholder-shown 选择器实现 label 浮动效果的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angular模块库开发实例
- 下一篇: 12.10 Nginx访问日志 12.1