如果文本字段为空,请更改按钮元素的样式 [英] Change style of button element if text field is empty

查看:112
本文介绍了如果文本字段为空,请更改按钮元素的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变 #postBtn 的风格,如果 #textfield 为空, >

I would like to change style of #postBtn, if #textfield is empty, something like

#postBtn:[#textfield.value.length==0]{
         border-color:gray;
         background-color:gray;
}

在html中:

<input id='textfield'>
<input type="button"  Value="Post" onClick="post()" id="postBtn">

如何在没有javascript的情况下实现?
谢谢!

How do I achieve this without javascript? Thanks!

推荐答案

好的,你可以添加 required 到您的输入字段如下:

Ok, you can add required to your input field like so:

<input id='textfield' required>
<input type="button"  Value="Post" onClick="post()" id="postBtn">

然后,使用:invalid 相邻兄弟选择器( + ),如果字段为空,您可以对按钮设置样式,如下所示:

And then, using :invalid and the adjacent sibling selector (+), you can style the button if the field is empty like so:

#textfield:invalid + #postBtn {
    background-color: red;
}



这里是一个小小的动作: http://jsfiddle.net/w7377/

注意: / strong>如果文本输入字段实际上不是必填字段,则此解决方案不是要走的路。如果是这样,您可能必须使用Javascript解决方案。

Note: If the text input field is not actually a required field, then this solution is not the way to go. You may have to use a Javascript solution if that's the case.

这篇关于如果文本字段为空,请更改按钮元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆