2017-02-22 86 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然後如果你專注,它不會被刪除 –