P粉7104789902023-08-21 12:14:04
You can use :placeholder-shown
pseudo-class. Technically, a placeholder is required, but you can use a space instead.
input:not(:placeholder-shown) { border-color: green; } input:placeholder-shown { border-color: red; }
<input placeholder="需要文本" /> <input placeholder=" " value="这个有效" /> <input placeholder=" " />
P粉4156323192023-08-21 09:35:11
StylishCan't do this because CSS doesn't make it possible. CSS has no (pseudo) selectors for <input>
values. See:
:empty
The selector only applies to child nodes, not to input values.
[value=""]
can work; but only in the initial state. This is because the node's value
property seen by CSS is different from the node's value
property (changed by the user or DOM JavaScript, and submitted as form data).
Unless you only care about the initial state, you must use a user script or a Greasemonkey script. Fortunately, this is not difficult. The following script will work in Chrome, or in Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).
See a demonstration of CSS limitations and JavaScript solutions on this jsBin page .
// ==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"; }