【问题标题】:CSS3 - style on focused parent element [duplicate]CSS3 - 聚焦父元素的样式[重复]
【发布时间】:2013-07-31 04:57:13
【问题描述】:

我知道我可以像这样在焦点输入元素上设置样式:

input:focus
{ 
  background-color:yellow;
}

但是当输入有焦点时,是否有可能在父元素上设置样式? 例如

<div class="foo">
      <input type="text />
      Hello
</div>

输入有焦点时,我可以影响“foo”样式吗?

编辑: Affecting parent element of :focus'd element (pure CSS+HTML preferred)的可能重复

但是,有人能解释一下它是如何工作的吗?

【问题讨论】:

    标签: html css


    【解决方案1】:

    css 中没有父选择器(目前)。 http://css-tricks.com/parent-selectors-in-css/

    但是,您可以使用 jQuery 选择它:

    html

    <div class="parent">
        <input type="text" />
    </div>
    

    css

    .parent {
        /* parent styles */
    }
    .parent.active {
        /* do stuff when the input is hovered */
    }
    

    js

    // listen for a focus event on the input,
    //  and then add a class to the parent
    $('input').on('focus', function () {
        $(this).parent().addClass('active');
    });
    

    http://jsfiddle.net/M64nv/

    【讨论】:

    • 太棒了,如果父级已经包含一个特定的类,有没有办法只将该类应用到父级?例如如果父级有“input-append”和/或“input-prepend”类?
    • 当然,只需将类作为参数添加到 .parent() 选择器,例如 $(this).parent('input-append').addClass('active');
    【解决方案2】:

    没有。 CSS 中没有父选择器,因此当父元素之一悬停时(或基于任何子元素条件),您无法在父元素上触发样式规则。为此,您需要使用 Javascript。

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多