如何使用sass将父div定位在子div的焦点上?

时间:2019-02-19 18:29:13

标签: html5 sass

我如何才能使“专注于输入”更改文本的背景颜色呢?  我到底在做什么错? 请告诉我.. 谢谢

.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>

2 个答案:

答案 0 :(得分: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');
})

答案 1 :(得分:0)

实际上这现在是可行的,但可能在任何情况下都不可行:

借助:focus-withinhttps://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>

相关问题