<p>有没有办法通过CSS来检测输入框是否有文本?我尝试使用<code>:empty</code>伪类和<code>[value=""]</code>,但都没有成功。我似乎找不到一个解决方案。</p>
<p>我想这一定是可能的,考虑到我们有<code>:checked</code>和<code>:indeterminate</code>这样的伪类,它们都是类似的东西。</p>
<p>请注意:<strong>我是为了一个“Stylish”样式而做这个</strong>,不能使用JavaScript。</p>
<p>还要注意,Stylish是在用户无法控制的页面上使用的,客户端的。</p>
您可以使用
:placeholder-shown伪类。技术上来说,需要一个占位符,但您可以使用一个空格代替。input:not(:placeholder-shown) { border-color: green; } input:placeholder-shown { border-color: red; }Stylish无法做到这一点,因为CSS无法实现这一点。CSS没有(伪)选择器适用于
<input>值。请参阅::empty选择器仅适用于子节点,而不适用于输入值。[value=""]可以工作;但仅适用于初始状态。这是因为CSS所看到的节点的value属性与节点的value属性不同(由用户或DOM JavaScript更改,并作为表单数据提交)。除非您只关心初始状态,您必须使用用户脚本或Greasemonkey脚本。幸运的是,这并不难。以下脚本将在Chrome中工作,或者在安装了Greasemonkey或Scriptish的Firefox中工作,或者在支持用户脚本的任何浏览器中(即大多数浏览器,除了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"; }