无法点击具有负z-index的文本框

9
我在屏幕中间有一个文本框,但是当我点击它时,没有任何反应。我认为这是CSS Z-Index的问题。如何诊断和解决这个问题? JsFiddle

div#container {
    z-index:-1;
    position:relative;
    height:300px;
    width:300px;
    margin:0 auto;
    background-color: #E9E9E9;
    box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.25);
    padding-top: 8px;
}
h2 {
    text-align:center;
}
#container input[type="submit"] {
    position:absolute;
    bottom:0;
    left:0;
    height:50px;
    width:100%;
}
#container input[type="text"], #container input[type="password"] {
    position:absolute;
    outline:0;
    border:none;
    padding:0;
    margin:0;
    height:50px;
    top:50px;
    width:100%;
}
#container input[type="password"] {
    top:150px;
}
.overlay {
    position:absolute;
    top:0;
    left:0;
    z-index:2;
    height:100%;
    width:100%;
    background:gray;
    text-align:center;
    line-height:300px;
    box-shadow:inset 0 120px 0 0 darkgray, inset 0 122px 0 0 gray, inset 0 124px 0 0 darkgray, inset 0 -120px 0 0 darkgray, inset 0 -122px 0 0 gray, inset 0 -124px 0 0 darkgray;
}
body:hover .overlay {
    display:none;
}
<div id="container">
     <h2>LOGIN</h2>

    <input type="text" id="name" placeholder="Enter your Name" />
    <input type="password" id="password" placeholder="Enter your Password" />
    <input type="submit" id="submit" value="Login" />
    <div class="overlay">LOGIN HERE</div>
</div>

我的问题是我无法实际点击输入框。我尝试了调整布局,但似乎无法使输入框“可点击”。
请问有人能解释如何解决这个问题吗?
2个回答

12

Z-index应该用于在其他元素的上方/下方叠放实际元素,对于输入框来说不应该给予负值,特别是当你的body元素被默认设置为0时。

这意味着设置小于0的值(即负值)将使您的元素被放置在body后面。

因此,如果这是一个输入元素,你实际上无法点击它,因为'你会点击到body而非输入框本身'


在罕见情况下,你需要给输入框添加z-index(大多数时候不需要声明),与其设置负值,建议使用较低的正值。这样它应该在body上面(除非已更改设置)。

以下是一个简短的示例:

body {
  background: tomato;
}
input {
  z-index: -2;
  position: relative;
}
<input type="text" placeholder="i'm unclickable!" />


By using a positive value (0 or greater), you can then select the textbox

body{
  background:tomato;
  }
input{
  position:relative;
  z-index:0;
  }
<input type="text" placeholder="i'm now clickable!"/>

在上面的示例中,您最终可以完全删除z-index。

有关z-index属性的更多信息,请参阅其文档


JsFiddle解决方案


7
问题出在 div#container 元素的 z-index 属性被赋值为 -1。
将元素的 z-index 设置为一些更高的值,如 1000 等。
div#container {

    background-color: #E9E9E9;
    box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.25);
    clear: left;
    height: 75px;
    margin: 0 auto 13px;
    overflow: auto;
    padding-top: 8px;
    position: relative;
    text-align: center;
    width: 510px;
    z-index: 1000;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接