有没有办法通过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";
}

Css相关问答推荐

在React Native中使用绝对位置对图像进行居中

如何在css中从圆中切出1/n?

无限交替css动画之间的未知延迟

向左或向右浮动时的不同图像边距

如何在Bootstrap 5上使用移动设备居中内容?

CSS关键帧中使用transform-origin存在问题的解决方案

动态覆盖 Vuetify 类

有人可以解释为什么我的 CSS 转换如此突然吗?

在 Tailwind css 中,间距对我不起作用

条件宽度和省略号不适用于样式化组件 - React.js

Tailwind:如何设置网格的自动填充?

CSS背景位置从顶部的给定像素开始?

普通流,流布局,块和内联布局有什么区别?

修复导航栏隐藏页面内容

在 中制作等宽的列

表格的边框半径没有按预期工作

仅针对直接子代而不是其他相同后代的 CSS Select 器

CSS图像最大宽度设置为原始图像大小?

删除行内块元素中大文本上方和下方的空白

如何实现最大字体大小?