您可以使用:placeholder-shown
偽類。技術上來說,需要一個占位符,但您可以使用一個空格代替。
input:not(:placeholder-shown) { border-color: green; } input:placeholder-shown { border-color: red; }
<input placeholder="需要文本" /> <input placeholder=" " value="這個有效" /> <input placeholder=" " />
Stylish無法做到這一點,因為CSS無法實現(xiàn)這一點。CSS沒有(偽)選擇器適用于<input>
值。請參閱:
:empty
選擇器僅適用于子節(jié)點,而不適用于輸入值。
[value=""]
可以工作;但僅適用于初始狀態(tài)。這是因為CSS所看到的節(jié)點的value
屬性與節(jié)點的value
屬性不同(由用戶或DOM JavaScript更改,并作為表單數(shù)據(jù)提交)。
除非您只關心初始狀態(tài),您必須使用用戶腳本或Greasemonkey腳本。幸運的是,這并不難。以下腳本將在Chrome中工作,或者在安裝了Greasemonkey或Scriptish的Firefox中工作,或者在支持用戶腳本的任何瀏覽器中(即大多數(shù)瀏覽器,除了IE)。
在這個jsBin頁面上查看CSS限制和JavaScript解決方案的演示。
// ==UserScript== // @name _Dynamically style inputs based on whether they are blank. // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @grant GM_addStyle // ==/UserScript== /*- The @grant directive is needed to work around a design change introduced in GM 1.0. It restores the sandbox. */ var inpsToMonitor = document.querySelectorAll ( "form[name='JustCSS'] input[name^='inp']" ); for (var J = inpsToMonitor.length - 1; J >= 0; --J) { inpsToMonitor[J].addEventListener ("change", adjustStyling, false); inpsToMonitor[J].addEventListener ("keyup", adjustStyling, false); inpsToMonitor[J].addEventListener ("focus", adjustStyling, false); inpsToMonitor[J].addEventListener ("blur", adjustStyling, false); inpsToMonitor[J].addEventListener ("mousedown", adjustStyling, false); //-- Initial update. note that IE support is NOT needed. var evt = document.createEvent ("HTMLEvents"); evt.initEvent ("change", false, true); inpsToMonitor[J].dispatchEvent (evt); } function adjustStyling (zEvent) { var inpVal = zEvent.target.value; if (inpVal && inpVal.replace (/^\s+|\s+$/g, "") ) zEvent.target.style.background = "lime"; else zEvent.target.style.background = "inherit"; }