使用 CSS 检测输入中是否包含文本——在我正在访问的页面上并且不控制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16952526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:08:06  来源:igfitidea点击:

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

cssinputis-emptystylish

提问by JacobTheDev

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

有没有办法通过 CSS 检测输入是否包含文本?我试过使用:empty伪类,也试过使用[value=""],但都没有奏效。我似乎无法找到解决此问题的单一解决方案。

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

我想这一定是可能的,考虑到我们有伪类的:checked,和:indeterminate,这两者都是那种类似的事情。

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

请注意:我这样做是为了“时尚”风格,它不能使用 JavaScript。

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

另请注意,在用户无法控制的页面上使用 Stylish,客户端。

采纳答案by Brock Adams

Stylishcannot do this because CSS cannot do this. CSS has no (pseudo) selectors for <input>value(s).See:

Stylish无法做到这一点,因为 CSS 无法做到这一点。 CSS 没有(伪)<input>值选择器。看:

The :emptyselector refers only to child nodes, not input values.
[value=""]doeswork; but only for the initialstate. This is because a node's valueattribute(that CSS sees), is not the same as the node's valueproperty(Changed by the user or DOM javascript, and submitted as form data).

:empty选择仅指子节点,而不是输入值。
[value=""]确实有效;但仅限于初始状态。这是因为节点的value属性(CSS 看到的)与节点的value属性(由用户或 DOM javascript 更改,并作为表单数据提交)不同。

Unless you care only about the initial state, you mustuse a userscript or Greasemonkey script.Fortunately this is not hard. The following script will work in Chrome, or Firefox with Greasemonkey or Scriptish installed, or in any browser that supports userscripts (i.e. most browsers, except IE).

除非你只关心初始状态,必须使用一个userscript或Greasemonkey的脚本。幸运的是,这并不难。以下脚本将在 Chrome 或安装了 Greasemonkey 或 Scriptish 的 Firefox 或任何支持用户脚本的浏览器(即大多数浏览器,IE 除外)中运行。

See a demo of the limits of CSS plus the javascript solution at this jsBin page.

此 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";
}

回答by Jukka K. Korpela

It is possible, with the usual CSS caveats and if the HTML code can be modified. If you add the requiredattribute to the element, then the element will match :invalidor :validaccording to whether the value of the control is empty or not. If the element has no valueattribute (or it has value=""), the value of the control is initially empty and becomes nonempty when any character (even a space) is entered.

这是可能的,通常的 CSS 警告以及 HTML 代码是否可以修改。如果将required属性添加到元素中,则元素将匹配:invalid:valid根据控件的值是否为空。如果元素没有value属性(或有value=""),则控件的值最初为空,并在输入任何字符(甚至是空格)时变为非空。

Example:

例子:

<style>
#foo { background: yellow; }
#foo:valid { outline: solid blue 2px; }
#foo:invalid { outline: solid red 2px; }
</style>
<input id=foo required>

The pseudo-classed :validand :invalidare defined in Working Draft level CSS documents only, but support is rather widespread in browsers, except that in IE, it came with IE 10.

伪类:valid:invalid仅在工作草案级别的 CSS 文档中定义,但在浏览器中的支持相当广泛,除了在 IE 中,它随 IE 10 一起提供。

If you would like to make “empty” include values that consist of spaces only, you can add the attribute pattern=.*\S.*.

如果您想让“空”包含仅由空格组成的值,您可以添加属性pattern=.*\S.*

There is (currently) no CSS selector for detecting directly whether an input control has a nonempty value, so we need to do it indirectly, as described above.

(目前)没有 CSS 选择器用于直接检测输入控件是否具有非空值,因此我们需要间接进行,如上所述。

Generally, CSS selectors refer to markupor, in some cases, to element properties as set with scripting (client-side JavaScript), rather than user actions. For example, :emptymatches element with empty content in markup; all inputelements are unavoidably empty in this sense. The selector [value=""]tests whether the element has the valueattribute in markup and has the empty string as its value. And :checkedand :indeterminateare similar things. They are not affected by actual user input.

通常,CSS 选择器指的是标记,或者在某些情况下指的是使用脚本(客户端 JavaScript)设置的元素属性,而不是用户操作。例如,:empty匹配标记中内容为空的元素;input从这个意义上说,所有元素都不可避免地是空的。选择器[value=""]测试元素是否具有value标记中的属性并以空字符串作为其值。而且:checked:indeterminate是类似的东西。它们不受实际用户输入的影响。

回答by ngryman

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

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

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=" " />

回答by Tom D.

<input onkeyup="this.setAttribute('value', this.value);" />

and

input[value=""]

will work :-)

将工作 :-)

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

编辑:http: //jsfiddle.net/XwZR2/

回答by Fábio ZC

Basically what everybody is looking for is:

基本上每个人都在寻找的是:

LESS:

较少的:

input:focus:required{
    &:invalid{ color: red; border-color: red; box-shadow: 0 0 6px red;}
    &:valid,
    &:placeholder-shown{ border-color: green; box-shadow: 0 0 8px green;}
}

Pure CSS:

纯 CSS:

input:focus:required:invalid{ color: red; border-color: red; box-shadow: 0 0 6px red;}
input:focus:required:valid,
input:focus:required:placeholder-shown{ border-color: green; box-shadow: 0 0 8px green;}

回答by Ricky Levi

You can use the placeholdertrick as written above w/o requiredfield.

您可以使用placeholder上面写的不带required字段的技巧。

The problem with requiredis that when you wrote something, then deleted it - the input will now always be red as part of the HTML5 spec - then you'll need a CSS as written above to fix/override it.

问题required在于,当你写了一些东西,然后删除了它——作为 HTML5 规范的一部分,输入现在总是红色的——然后你需要一个如上所述的 CSS 来修复/覆盖它。

You can simple do thing w/o required

你可以简单地做没有/没有的事情 required

<input type="text" placeholder="filter here" id="mytest" />

CSS

CSS

#mytest:placeholder-shown {
/* if placeholder is shown - meaning - no value in input */
  border: black 1px solid;
  color: black;
}
#mytest {
  /* placeholder isn't shown - we have a value in input */
  border: red 1px solid;
  color: red;
}

Code pen:https://codepen.io/arlevi/pen/LBgXjZ

代码笔:https: //codepen.io/arlevi/pen/LBgXjZ

回答by Breno Teixeira

Simple css:

简单的CSS:

input[value]:not([value=""])

This code is going to apply the given css if the input is filled up.

如果输入已填满,此代码将应用给定的 css。

回答by vbraun

You can style input[type=text]differently depending on whether or not the input has text by styling the placeholder. This is not an official standard at this point but has wide browser support, though with different prefixes:

您可以input[type=text]通过设置占位符样式,根据输入是否包含文本来设置不同的样式。这在这一点上还不是官方标准,但具有广泛的浏览器支持,尽管具有不同的前缀:

input[type=text] {
    color: red;
}
input[type=text]:-moz-placeholder {
    color: green;
}
input[type=text]::-moz-placeholder {
    color: green;
}
input[type=text]:-ms-input-placeholder {
    color: green;
}
input[type=text]::-webkit-input-placeholder {
    color: green;
}

Example: http://fiddlesalad.com/scss/input-placeholder-css

示例:http: //fiddlesalad.com/scss/input-placeholder-css

回答by Pavlo Kozachuk

Using JS and CSS :not pseudoclass

使用 JS 和 CSS:不是伪类

 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="" />

   

回答by Niels Steenbeek

The valid selectorwill do the trick.

有效的选择会做的伎俩。

<input type="text" class="myText" required="required" />

.myText {
    //default style of input
}
.myText:valid {
    //style when input has text
}