CSS :focus-within 选择器用于具有 iframe 子元素的元素

Eth*_*han 5 css iframe focus css-selectors pseudo-class

我有一个这样的场景:

.container {
  background: yellow;
  padding: 40px;
}

.container:focus-within {
  background: red;
}

iframe {
  background: white;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <input type="text" placeholder="Input 1">
  <iframe srcdoc="<input type='text' placeholder='Input 2'>"></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

如您所见,当我单击输入 1 进行输入时,由于 :focus-within选择器。但是当我关注输入 2(在 iframe 内)时,它没有。

.container如果 iframe 中的某些内容被聚焦,是否可以使用 CSS 选择器?我也可以控制 iframe 内的 CSS。

Erc*_*ker 2

不是通过CSS,而是通过jQuery,您可以在输入2聚焦时将类添加到容器,并在失去焦点时删除类。

<style>
 .container:focus-within, .container.in_iframe {
            background: red;
        }
</style>

<script>
    $('document').ready(function () {
        $('#iframe').on('load', function () {
            var iframe = $('#iframe').contents();
            iframe.find("input").on('focus', function () {
                $('.container').addClass('in_iframe');
            });
            iframe.find("input").on('focusout', function () {
                $('.container').removeClass('in_iframe');
            });
        });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

完整代码: https: //codepen.io/peker-ercan/pen/PdgEOy