有没有办法通过CSS检测输入中是否包含文本?我try 过使用:empty
伪类,也try 过使用[value=""]
,但这两种方法都不起作用.我似乎找不到一个单一的解决方案.
我想这肯定是可能的,考虑到我们有:checked
和:indeterminate
的伪类,这两个类都有点类似.
请注意:I'm doing this for a "Stylish" style,它不能使用JavaScript.
还要注意的是,客户端在用户不能控制的页面上使用这种风格.
有没有办法通过CSS检测输入中是否包含文本?我try 过使用:empty
伪类,也try 过使用[value=""]
,但这两种方法都不起作用.我似乎找不到一个单一的解决方案.
我想这肯定是可能的,考虑到我们有:checked
和:indeterminate
的伪类,这两个类都有点类似.
请注意:I'm doing this for a "Stylish" style,它不能使用JavaScript.
还要注意的是,客户端在用户不能控制的页面上使用这种风格.
Stylish无法执行此操作,因为CSS无法执行此操作.CSS has no (pseudo) selectors for 100 value(s).请参阅:
The :empty
selector refers only to child nodes, not input values.
[value=""]
does work; but only for the initial state. This is because a node's value
attribute (that CSS sees), is not the same as the node's value
property (Changed by the user or DOM javascript, and submitted as form data).
除非你只关心初始状态,you must use a userscript or Greasemonkey script.幸运的是这并不难.下面的脚本可以在Chrome或安装了Gresemonkey或Scripish的Firefox中运行,也可以在任何支持用户脚本的浏览器中运行(即大多数浏览器,IE除外).
请看CSS的限制以及this jsBin page的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";
}