当其他元素获得焦点时输入失去焦点

input lose focus when other element is focused

我正在尝试仅使用 CSS 和 HTML 创建自定义组件。 组件的行为类似于:当输入被选中(有焦点)时,另一个容器被打开。 问题是当容器打开时输入失去焦点并且容器在第一次单击时关闭:(

那么当我聚焦在打开的容器上时,如何才能使输入聚焦?

<div class="block">
    <label>Field</label>
    <input type="text" tabindex="-1"/>
    <div tabindex="-1" class="infront">
         Keep this bastard open.<br/>
        <br/>
        while clicking on this div
    </div>
</div>

CSS

.block{
    position: relative;
    display: inline-block;
    margin: 50px;
}

.infront{display: none;}

.block input[type="text"]:focus ~ .infront {
    display: block;
    position: absolute;
    top:100%;
    width: 80%;
    right: 0;
    background: #ccc;
    opacity:0.8;
}

Fiddle:

我认为你不能只用 HTML 和 CSS 来做。您将需要像这样的 jquery 代码:

$(.block input[type=text]).on('focus', function(e) {
    $('.infront').show();
});

您还需要处理 .infront 容器状态的状态。

将您的 CSS 更新为此

.block input[type="text"]:focus ~ .infront
, .infront:hover
, .infront:active 
, .infront:focus {
    display: block;
    position: absolute;
    top:100%;
    width: 80%;
    right: 0;
    background: #ccc;
    opacity:0.8;
}