我有这样一个场景:
.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>
关于CSS :focus-within selector for an element with an iframe child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463332/