【问题标题】:how to target parent div on focus of child div using sass.?如何使用 sass 将父 div 定位在子 div 的焦点上。?
【发布时间】:2023-03-16 05:40:02
【问题描述】:

我怎样才能让它专注于输入来改变文本的背景颜色..? 我到底做错了什么? 请告诉我.. 谢谢

.parent_div {
  background: lightblue;
  .child_div {
    input {
      color: grey;
      background: blue;
      &:focused {
        color: purple;
        background: white;
      }
      &:focused~grand-child-of-parent {
        opacity: 0.7;
        background: red;
      }
    }
  }
}
<div class="parent_div">
  <div class="first_child">
    <input type="text" />
  </div>
  <p class="second_child"> is simply dummy text of the printing and typesetting industry.</p>
</div>

【问题讨论】:

标签: html sass


【解决方案1】:

很遗憾,这是不可能的,因为没有“祖父”选择器。

当输入获得焦点时,您可以更改输入本身的背景和文本,但如果不使用 JavaScript,则无法修改父元素的样式。

对于这种情况,通过 JavaScript 监听焦点事件并添加/删除修饰符类,例如父元素。

HTML:

<div class="parent-class">
  <input class="field" type="text" />
  <div class="child-class">
    <p>Bla</p>
  </div>
</div>

CSS:

.child-class {
  background: red;
}
.focused .child-class {
  background: green;
}

JavaScript (jQuery):

$('.field').on('focus', function() {
  $(this).parent().addClass('focused');
})
$('.field').on('blur', function() {
  $(this).parent().removeClass('focused');
})

【讨论】:

    【解决方案2】:

    实际上这现在有点可能,但在任何情况下都不可能:

    :focus-within (https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within) 的帮助下。

    .parent_div {
      background: lightblue;
    }
    
    .parent_div .first_child .input {
      color: grey;
      background: blue;
    }
    
    .parent_div .first_child .input:focus {
      color: purple;
      background: white;
    }
    
    .parent_div:focus-within {
      opacity: 0.7;
      background: red;
    }
    <div class="parent_div">
      <div class="first_child">
        <input class="input" type="text" />
      </div>
      <p class="second_child"> is simply dummy text of the printing and typesetting industry.</p>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 2017-05-28
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多