2017-08-12 40 views
0

我有一個容器div,裏面有一個隱藏的button,它只有在關注容器div時纔會出現。我想在聚焦時讓button可見(我想讓它可以聚焦)。這裏有一個fiddle如何僅在使用CSS集中時顯示隱藏按鈕?

HTML

<div class="ads" tabindex="0"> 
    <button class="close" tabindex="0">X</button> 
</div> 

CSS

.ads{ 
    position: relative; 
    display: inline-block; 
    border-radius: 0.5625rem; 
    border-style: solid; 
    border-width: 0.03125rem; 
    border-color: lightgrey; 
    background-color: #ffffff; 
    width: 100%; 
    height: 80px; 
} 
.close{ 
     display: none; 
     padding: 0; 
     background: transparent; 
     border: none; 
     margin-top: 0.5rem; 
     margin-right: 0.5rem; 
     float: right; 
     width: 0.5rem; 
     height: 0.5rem; 
     background-image: url('delete.png'); 
     background-size: 100% 100%; 
} 
div.ads:focus{ 
    background-color: #ebeded; 
} 
div.ads:focus .close{ 
    display:inline-block; 
} 
button.close:focus{ 
    display:inline-block; 
} 

我怎樣才能做到這一點?

謝謝。

+1

焦點......可聚焦......什麼? –

+0

@Roko C. Buljan是的,使事件:專注於它與標籤鍵 – user6561572

+0

它實際上工作。看[這裏](https://jsfiddle.net/6m51xdtb/3/)我改變了焦點的背景,所以你可以看到(我使用鉻) – avrahamcool

回答

0

在任何給定的時刻,只有一個元素可以聚焦或沒有。

但是,您的解決方案假定文檔中有兩個元素同時匹配:focus

這裏是事件的順序,當你按下集中的div標籤:

  1. 你DIV失去專注所以不匹配:焦點;
  2. 按鈕被隱藏,因爲它還沒有獲得焦點;
  3. 因爲div內沒有任何可見/可聚焦的東西,所以焦點移動到別的東西上,而不是按鈕上。

您應該找到其他解決方案。

更新:可能的CSS只有黑客是使用不透明度:0代替display:none。 這裏的黑客是認爲opacity:0元素仍然是顯示元素,因此可以聚焦。

input{ 
 
    display: block; 
 
    width: 100%; 
 
} 
 
.ads{ 
 
    position: relative; 
 
    display: inline-block; 
 
    border-radius: 0.5625rem; 
 
    border-style: solid; 
 
    border-width: 0.03125rem; 
 
    border-color: lightgrey; 
 
    background-color: #ffffff; 
 
    width: 100%; 
 
    height: 80px; 
 
} 
 

 
.close{ 
 
     opacity: 0; 
 
     padding: 0; 
 
     background: transparent; 
 
     border: none; 
 
     margin-top: 0.5rem; 
 
     margin-right: 0.5rem; 
 
     float: right; 
 
     width: 0.5rem; 
 
     height: 0.5rem; 
 
     background-image: url('delete.png'); 
 
     background-size: 100% 100%; 
 
} 
 

 
div.ads:focus{ 
 
    background-color: #ebeded; 
 
} 
 
div.ads:focus .close{ 
 
    opacity: 1.0; 
 
} 
 
button.close:focus{ 
 
    opacity: 1.0; 
 
}
<input type="text" placeholder="press on me and tab two times"> 
 
<div class="ads" tabindex="0"> 
 
    <button class="close" tabindex="0">X</button> 
 
</div> 
 
<p> 
 
by the second tab you should see focused button ,but you don't 
 
</p>

+0

,但是當我:專注於按鈕,我通過顯示可見:內聯塊是不夠的?我覺得我在搞點什麼 – user6561572

+1

在#1你的div沒有:焦點和按鈕沒有:焦點呢。所以它是無形的/不可聚焦的 –

+0

很好的一步一步的解釋。 –