是否有可能禁用表单字段使用CSS?我当然知道禁用属性,但是否有可能在CSS规则中指定这一点?比如——

<input type="text" name="username" value="admin" >
<style type="text/css">
  input[name=username] {
    disabled: true; /* Does not work */
  }
</style>

我问的原因是,我有一个应用程序,其中表单字段是自动生成的,字段隐藏/显示基于一些规则(在Javascript中运行)。现在我想扩展它以支持禁用/启用字段,但规则的编写方式是直接操作表单字段的样式属性。因此,现在我必须扩展规则引擎来更改属性以及表单字段的样式,但不知何故,这似乎不太理想。

奇怪的是,CSS中有可见和显示属性,但没有启用/禁用。在尚未开发的HTML5标准或非标准(特定于浏览器)中是否存在类似内容?


当前回答

没有办法使用CSS来实现这个目的。 我的建议是包括一个javascript代码,你分配或改变css类应用到输入。 就像这样:

function change_input() { $('#id_input1') .toggleClass('class_disabled') .toggleClass('class_enabled'); $('.class_disabled').attr('disabled', ''); $('.class_enabled').removeAttr('disabled', ''); } .class_disabled { background-color : #FF0000; } .class_enabled { background-color : #00FF00; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form> Input: <input id="id_input1" class="class_enabled" /> <input type="button" value="Toggle" onclick="change_input()";/> </form>

其他回答

这可以通过在输入元素上叠加来实现非关键目的。下面是纯HTML和CSS的例子。

https://jsfiddle.net/1tL40L99/

    <div id="container">
        <input name="name" type="text" value="Text input here" />
        <span id="overlay"></span>
    </div>

    <style>
        #container {
            width: 300px;
            height: 50px;
            position: relative;
        }
        #container input[type="text"] {
            position: relative;
            top: 15px;
            z-index: 1;
            width: 200px;
            display: block;
            margin: 0 auto;
        }
        #container #overlay {
            width: 300px;
            height: 50px;
            position: absolute;
            top: 0px;
            left: 0px;
            z-index: 2;
            background: rgba(255,0,0, .5);
        }
    </style>

我一直在用:

input.disabled {
  pointer-events:none;
  color:#AAA;
  background:#F5F5F5;
}

然后将CSS类应用到输入字段:

<input class="disabled" type="text" value="90" name="myinput" id="myinput" />

输入(name =用户名){ 禁用:真实;/*不起作用*/}

我知道这个问题很老了,但对于遇到这个问题的其他用户来说,我认为禁用输入的最简单的方法就是通过':disabled'

<input type="text" name="username" value="admin" disabled />
<style type="text/css">
  input[name=username]:disabled {
    opacity: 0.5 !important; /* Fade effect */
    cursor: not-allowed; /* Cursor change to disabled state*/
  }
</style>

在现实中,如果你有一些脚本来禁用输入动态/自动与javascript或jquery,将自动禁用基于你添加的条件。

以jQuery为例:

if (condition) {
// Make this input prop disabled state
  $('input').prop('disabled', true);
}
else {
// Do something else
}

希望CSS中的答案能有所帮助。

你可以使用CSS来伪装禁用效果。

pointer-events:none;

你可能还想改变颜色等等。

既然规则是在JavaScript中运行的,为什么不使用JavaScript(或者在我的例子中使用jQuery)禁用它们呢?

$('#fieldId').attr('disabled', 'disabled'); //Disable
$('#fieldId').removeAttr('disabled'); //Enable

更新

attr函数不再是主要的方法,正如在下面的评论中指出的那样。这是用prop函数完成的。

$( "input" ).prop( "disabled", true ); //Disable
$( "input" ).prop( "disabled", false ); //Enable