【发布时间】:2022-06-15 22:37:52
【问题描述】:
我正在研究我从 youtube 视频制作的输入设计,它运行良好,但我想稍微修改一下,代码:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
flex-direction: column;
gap: 30px;
background: #1d2b3a;
}
/******************** Input Box - Not Required ********************/
.inputBox{
position: relative;
width: 250px;
}
.inputBox input{
width: 100%;
padding: 10px;
border: 1px solid rgba(255,255,255,0.25);
background: #1d2b3a;
border-radius: 5px;
outline: none;
color: #fff;
font-size: 1em;
transition: 0.5s;
}
.inputBox span{
position: absolute;
left: 0;
padding: 10px;
pointer-events: none;
font-size: 1em;
color: rgba(255,255,255, 0.25);
text-transform: uppercase;
transition: 0.5s;
}
.inputBox input:invalid ~ span,
.inputBox input:focus ~ span{
color: #00dfc4;
transform: translateX(10px) translateY(-7px);
font-size: 0.65em;
padding: 0 10px;
background: #1d2b3a;
border-left: 1px solid #00dfc4;
border-right: 1px solid #00dfc4;
letter-spacing: 0.2em;
}
.inputBox input:invalid,
.inputBox input:focus{
border: 1px solid #00dfc4;
}
/******************** Input Box - Required ********************/
.inputBox_r{
position: relative;
width: 250px;
}
.inputBox_r input{
width: 100%;
padding: 10px;
border: 1px solid rgba(255,255,255,0.25);
background: #1d2b3a;
border-radius: 5px;
outline: none;
color: #fff;
font-size: 1em;
transition: 0.5s;
}
.inputBox_r span{
position: absolute;
left: 0;
padding: 10px;
pointer-events: none;
font-size: 1em;
color: rgba(255,255,255, 0.25);
text-transform: uppercase;
transition: 0.5s;
}
.inputBox_r input:valid ~ span,
.inputBox_r input:focus ~ span{
color: #00dfc4;
transform: translateX(10px) translateY(-7px);
font-size: 0.65em;
padding: 0 10px;
background: #1d2b3a;
border-left: 1px solid #00dfc4;
border-right: 1px solid #00dfc4;
letter-spacing: 0.2em;
}
.inputBox_r input:valid,
.inputBox_r input:focus{
border: 1px solid #00dfc4;
}
.inputBox_r input:valid ~ span,
.inputBox_r input:focus ~ span{
background: #00dfc4;
color: #1d2b3a;
border-radius: 2px;
}
**HTML:**
<div class="inputBox">
<input type="text" name="">
<span>First Name</span>
</div>
<br>
<div class="inputBox_r">
<input type="text" name="" required>
<span>Last Name</span>
</div>
如您所见,有两个输入,一个不是强制性的,另一个是强制性的,具有 必需属性。当您在第二个输入框中输入文本时,它会保持焦点状态,因为必填属性,这正是我想要的第一个输入框。
第一个输入框没有 必需的属性,这就是为什么即使我在其中输入文本并单击其他地方,它也会失去焦点并弄乱我的 css 样式。
那么有什么方法可以在输入文本但不传递必需属性的情况下将注意力集中在第一个输入上?
我到处搜索,但找不到任何东西。 对不起,如果我说错了,我是 HTML 和 CSS 的新手
【问题讨论】:
-
我无法重现您的问题,这不是所需输入的预期行为。
-
在侧节点上:您应该在输入上使用
aria-labelledby来引用可访问性的标签,或者使用具有for属性的实际标签元素。 -
您不能同时在多个地方获得焦点。您需要的是
:invalid的对应项,它适用于不需要的字段 - 这将是:blank,只是 CSS 级别 4,还没有任何浏览器支持。 -
还有一点需要考虑 - medium.com/simple-human/…