簡體   English   中英

z-index 奇怪的行為?

[英]z-index weird behavior?

鑒於下面的例子

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index: -99; opacity: .5; position: relative; } .d2>button { transform: translateY(50px); }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

為什么當按鈕移出它的父級時,它變得可點擊?

編輯:

我使用了transform: translateY(50px); 移動按鈕,但是我們也可以使用position:relative;top:50px; 移動按鈕但問題仍然存在。

在這里,您面臨一個隱藏的問題,而翻譯/不透明度在這里無關。 使用負z-index ,就像您將元素置於body后面(因為此元素的z-index設置為auto )。 然后body高度由它的流入內容(兩個 div)定義,使用 translate 簡單地將元素放置在 body 下方,因此我們可以到達它並單擊它。

讓我們添加一些邊框/背景以更好地查看問題:

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index:-1; position: relative; } .d2>button { transform: translateY(50px); } body { background:rgba(255,0,0,0.5); border:2px solid; } html { background:blue; }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

body是紅色方塊,你所有的元素都在它后面,按鈕被移到底部,不再被身體覆蓋。 如果您使用其他屬性移動按鈕而不更改body高度,也會發生同樣的情況。

如果你給身體增加一些高度,翻譯不會改變任何東西,因為按鈕將保持在body后面

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index: -1; position: relative; } .d2>button { transform: translateY(50px); } body { height:100vh; }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM