【问题标题】:CSS Input Type Selectors - Possible to have an "or" or "not" syntax?CSS 输入类型选择器 - 可能有“或”或“非”语法?
【发布时间】:2011-03-27 14:37:06
【问题描述】:

如果它们存在于编程中),

如果我有一个包含以下输入的 HTML 表单:

<input type="text" />
<input type="password" />
<input type="checkbox" />

我想将样式应用于type="text" 或type="password" 的所有输入。

或者,我会接受type != "checkbox" 的所有输入。

看来我必须这样做:

input[type='text'], input[type='password']
{
   // my css
}

有没有办法:

input[type='text',type='password']
{
   // my css
}

或

input[type!='checkbox']
{
   // my css
}

我环顾四周,似乎没有办法使用单个 CSS 选择器来做到这一点。

当然没什么大不了,但我只是一只好奇的猫。

有什么想法吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    CSS3 有一个名为 :not() 的伪类

    input:not([type='checkbox']) {    
        visibility: hidden;
    }
    <p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                          
    <ul>
      <li>text: (<input type="text">)</li>  
      <li>password (<input type="password">)</li>       
      <li>checkbox (<input type="checkbox">)</li> 
     </ul>

    多个选择器

    正如文森特所说,可以将多个:not()s 串在一起:

    input:not([type='checkbox']):not([type='submit'])
    

    CSS4,即supported in many of the latest browser releases,允许:not() 中有多个选择器

    input:not([type='checkbox'],[type='submit'])
    

    旧版支持

    所有现代浏览器都支持 CSS3 语法。在提出这个问题时,我们需要 IE7 和 IE8 的后备方案。一种选择是使用像 IE9.js 这样的 polyfill。另一个是利用 CSS 中的级联:

    input {
       // styles for most inputs
    }   
    
    input[type=checkbox] {
      // revert back to the original style
    } 
    
    input.checkbox {
      // for completeness, this would have worked even in IE3!
    } 
    

    【讨论】:

    • 不错的一个!谢谢。是否完全支持 CSS3 选择器? (我只关心 IE7+、FF3+、Safari 最近、Chrome 最近)
    • IE9+ 和所有其他现代浏览器都支持它。 quirksmode.org/css/contents.html#t37
    • 为了完整起见,如果您想执行多个“not”,那么这是要使用的语法: input:not([type='checkbox']):not([type='提交'])
    【解决方案2】:
    input[type='text'], input[type='password']
    {
       // my css
    }
    

    这是正确的做法。遗憾的是 CSS 不是一种编程语言。

    【讨论】:

    • 不过,你可以使用 Less CSS 或 Sass。
    • 少,是的!我喜欢它。
    猜你喜欢
    • 2013-08-07
    • 2020-03-23
    • 2017-11-21
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多