Detect if an input has text in it using CSS — on a

2019-01-01 08:33发布

Is there a way to detect whether or not an input has text in it via CSS? I've tried using the :empty pseudo-class, and I've tried using [value=""], neither of which worked. I can't seem to find a single solution to this.

I imagine this must be possible, considering we have pseudo-classes for :checked, and :indeterminate, both of which are kind of similar thing.

Please note: I'm doing this for a "Stylish" style, which can't utilize JavaScript.

Also note, that Stylish is used, client-side, on pages that the user does not control.

14条回答
不再属于我。
2楼-- · 2019-01-01 08:59

Yes! you can do it with simple basic attribute with value selector.

Use attribute selector with blank value and apply properties input[value='']

input[value=''] {
    background: red;
}
查看更多
妖精总统
3楼-- · 2019-01-01 09:04

Using JS and CSS :not pseudoclass

 input {
        font-size: 13px;
        padding: 5px;
        width: 100px;
    }

    input[value=""] {
        border: 2px solid #fa0000;
    }

    input:not([value=""]) {
        border: 2px solid #fafa00;
    }
<input type="text" onkeyup="this.setAttribute('value', this.value);" value="" />

   

查看更多
柔情千种
4楼-- · 2019-01-01 09:05

You can use the :placeholder-shown pseudo class. Technically a placeholder is required, but you can use a space instead.

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

input:placeholder-shown {
  border-color: red;
}
<input placeholder="Text is required" />
<input placeholder=" " value="This one is valid" />
<input placeholder=" " />

查看更多
公子世无双
5楼-- · 2019-01-01 09:05

This is not possible with css. To implement this you will have to use JavaScript (e.g. $("#input").val() == "").

查看更多
长期被迫恋爱
6楼-- · 2019-01-01 09:08

do it on the HTML part like this:

<input type="text" name="Example" placeholder="Example" required="" />

The required parameter will require it to have text in the input field in order to be valid.

查看更多
孤独总比滥情好
7楼-- · 2019-01-01 09:09
<input onkeyup="this.setAttribute('value', this.value);" />

and

input[value=""]

will work :-)

edit: http://jsfiddle.net/XwZR2/

查看更多
登录 后发表回答