Can't control page, but detect if input contains text via CSS
P粉850680329
P粉850680329 2023-08-20 18:25:33
0
2
404
<p>Is there a way to detect whether the input box has text through CSS? I tried using the <code>:empty</code> pseudo-class and <code>[value=""]</code> without success. I can't seem to find a solution. </p> <p>I guess it must be possible, considering we have pseudo-classes like <code>:checked</code> and <code>:indeterminate</code> which are similar things. </p> <p>Please note: <strong>I am doing this for a "Stylish" style</strong> and cannot use JavaScript. </p> <p>Also note that Stylish is used on a page that the user has no control over, client-side. </p>
P粉850680329
P粉850680329

reply all(2)
P粉415632319

StylishCan't do this because CSS doesn't make it possible. CSS has no (pseudo) selectors for <input> values. See:

:emptyThe 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 valueproperty seen by CSS is different from the node's valueproperty (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";
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!