Can I select empty textareas with CSS?

此生再无相见时 提交于 2019-11-29 12:25:37

问题


Is there a way that I can select a textarea such that $('#id_of_textarea').val() in jQuery will be ''? I tried using :empty. I saw that CSS provides a way to select empty inputs because the text is in the value attribute ([value=""]). Is there an attribute for the text in a textarea?

I'm looking for a selector that will work with CSS, not just jQuery.


回答1:


Best solution I can think of is a CSS 3 workaround. Set the field to required (and unset it on submit if need be). Then you can use

textarea:invalid { /* style here... probably want to remove box-shadow and such */ }



回答2:


You can use the :empty css pseudo-class.

See an example in jsfiddle.

In the example there is a button for dynamically add new empty textareas to the DOM, so you can see that the new elements also are affected with the pseudo-class.

The code in the example was tested in Firefox 5.0, Opera 11.50 and Chromium 12.

Also, you can see a good description for the :empty pseudo-class here.




回答3:


For those who are using AngularJS, you can use ng-class in your view to add a class to your textarea to know if it is empty or not.

HTML :

<textarea ng-model="myForm.myTextArea"
          ng-class="(myForm.myTextArea.length)?'not_empty':'empty'">
</textarea>

CSS :

textarea.empty {
    background-color:red;
}
textarea.not_empty {
    background-color:blue;
}

Here is a jsfiddle.



来源:https://stackoverflow.com/questions/7072576/can-i-select-empty-textareas-with-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!