CSS :focus-within selector for an element with an iframe child

标签 css iframe css-selectors focus pseudo-class

我有这样一个场景:

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

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

iframe {
  background: white;
}
<div class="container">
  <input type="text" placeholder="Input 1">
  <iframe srcdoc="<input type='text' placeholder='Input 2'>"></iframe>
</div>

如您所见,当我点击输入 1 进行输入时,由于 :focus-within 选择器,容器变为红色。但是当我关注输入 2(在 iframe 内)时,它不会。

是否可以在 .container 上使用 CSS 选择器来确定 iframe 中的某些内容是否获得焦点?我也可以控制 iframe 内的 CSS。

最佳答案

不是通过 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>

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

关于CSS :focus-within selector for an element with an iframe child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463332/

相关文章:

javascript - 在HTML5网页中添加内容为HTML4的&lt;iframe&gt;是否有冲突?

html - 将文本居中到页面而不是单元格

javascript - 使用通过 API 接收的字体定义作为前端的字符串

jquery - 如何将 childBrowser 用于 phonegap 应用程序

javascript - 如何删除 iframe 正文填充

css - 仅使用 CSS : Select first occurrence of class throughout whole document

html - 在图像上 Bootstrap 悬停层

javascript - 防止 Bootstrap Accordion 扩展到父 div 之外

css - 为什么.foo a :link, .foo a :visited {} selector override a:hover, a :active {} selector in CSS?

jquery - Jquery 中基于标签之间文本的选择器