2017-02-22 84 views
0

我正尝试仅使用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:

+0

对不起,我不能跟着你,我真的不明白是什么问题 – MKAD

+0

我觉得你的代码工作当输入聚焦时,“.infront”精 – Sharmila

+0

@MKAD容器被打开,如果我点击进入隐藏的“.infront”容器,因为输入失去焦点。我需要的是,如果我点击里面,然后隐藏,如果我点击外面的容器,打开该容器.... – BurebistaRuler

回答

1

您还需要注意.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; 
} 
+0

谢谢你的答案! – BurebistaRuler

1

我认为你不能只使用HTML和CSS。你将需要这样的一些jQuery代码:

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

不是真的,容器“.infront”是从我的CSS显示,因此不需要jQuery显示。我需要的是保持“.infront”容器的打开状态,如果点击该容器并隐藏容器,如果我点击该容器的外部... – BurebistaRuler

+0

@burebistaruler你是对的,但是如果你想保留这个显示:block,你必须改变它与JS然后如果你专注,它不会被删除 –