检查输入是否具有CSS的文本/值

时间:2022-06-01 17:49:51

I've looked around a bit but can only find JS solutions to this.

我看了一下,但只能找到JS解决方案。

Is there a way with CSS to detect if an input has any text entered?

有没有办法用CSS来检测输入是否输入了任何文本?

What I'm doing is basically this (cut out the irrelevant code for this question):

我正在做的基本上就是这个(删除这个问题的无关代码):

 .search-form input[type="text"] {
    width: 0 !important;
}
.search-form input[type="text"]:focus {
    width: 100% !important;
}

Essentially, clicking on the label expands the input to 100% of the page width. This works fine, but when you enter text and click off the input, it shrinks back to width:0 - therefore hiding the inputted text. Is there a way with CSS to prevent this behaviour and keep it at width:100% like when the input is :focus when there's text inputted?

实质上,单击标签会将输入扩展为页面宽度的100%。这样可以正常工作,但是当您输入文本并单击输入时,它会缩小回宽度:0 - 因此隐藏输入的文本。有没有办法用CSS来防止这种行为并保持宽度:100%就像输入是:当输入文本时焦点?

2 个解决方案

#1


8  

Try adding the "required" property to the text field in the HTML, and then add this to the CSS:

尝试将“required”属性添加到HTML中的文本字段,然后将其添加到CSS:

.search-form input[type="text"]:valid {
    width: 100% !important;
}

I would probably try to avoid all those !importants though.

我可能会尽量避免所有这些!重要的事情。

#2


0  

Not sure if it will work for your specific use case, but you could achieve the effect with a fake input, using contenteditable

不确定它是否适用于您的特定用例,但您可以使用contenteditable实现虚假输入的效果

Working Example

 .fakeInput {
     border: 1px solid red;
     display:inline;
     padding:2px; /* optional */
 }
 .fakeInput:focus {
     display:block;
     border: 2px solid blue;
     width:100%;
     height:1em;
 }

<div class="search-form">
    <div class="fakeInput" contenteditable="true"></div>
</div>

#1


8  

Try adding the "required" property to the text field in the HTML, and then add this to the CSS:

尝试将“required”属性添加到HTML中的文本字段,然后将其添加到CSS:

.search-form input[type="text"]:valid {
    width: 100% !important;
}

I would probably try to avoid all those !importants though.

我可能会尽量避免所有这些!重要的事情。

#2


0  

Not sure if it will work for your specific use case, but you could achieve the effect with a fake input, using contenteditable

不确定它是否适用于您的特定用例,但您可以使用contenteditable实现虚假输入的效果

Working Example

 .fakeInput {
     border: 1px solid red;
     display:inline;
     padding:2px; /* optional */
 }
 .fakeInput:focus {
     display:block;
     border: 2px solid blue;
     width:100%;
     height:1em;
 }

<div class="search-form">
    <div class="fakeInput" contenteditable="true"></div>
</div>