无法控制页面,但通过CSS检测输入是否包含文本
P粉850680329
P粉850680329 2023-08-20 18:25:33
0
2
500
<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>
P粉850680329
P粉850680329

全部回复(2)
P粉710478990

您可以使用:placeholder-shown伪类。技术上来说,需要一个占位符,但您可以使用一个空格代替。

input:not(:placeholder-shown) {
  border-color: green;
}

input:placeholder-shown {
  border-color: red;
}
<input placeholder="需要文本" />
<input placeholder=" " value="这个有效" />
<input placeholder=" " />
P粉415632319

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";
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!