jquery - CSS - 输入焦点时的样式父 div
问题描述
我正在尝试将相同的样式添加到焦点时与悬停.block
时相同的样式。input
当输入焦点集中时,将样式添加到输入的父级的最佳方法是什么?是否有仅 CSS 的解决方案或是否需要 JavaScript?如果是这样,jQuery 解决方案是可以接受的。
body {
padding: 1rem 2rem;
}
input {
background: transparent;
padding: 1rem;
outline: none;
border: none;
flex: 1;
}
input:hover {
border-color: red;
}
input:focus ~ .label,
input:not(:focus):valid ~ .label {
color: #868ca0;
font-weight: 700;
border-color: red;
top: -0.6rem;
/*padding: 0 0.5rem;*/
font-size: 14px;
background: #fff;
opacity: 1;
}
.label {
position: absolute;
left: 1rem;
top: 1.2rem;
pointer-events: none;
color: #666;
transition: 0.2s ease all;
}
.block {
padding-right: 1rem;
width: 300px;
margin: 1.3rem 0;
border-radius: 6px;
position: relative;
display: flex;
align-items: center;
font-size: 16px;
border: 2px solid #dadada;
}
.block:hover {
border-color: #bdbdbd;
}
.block:focus {
border-color: red;
}
.box {
height: 30px;
width: 30px;
border-radius: 50%;
background: orange;
}
<div class="block">
<input type="text" required/>
<span class="label">Name</span>
</div>
<div class="block">
<input type="password" required/>
<span class="label">Password</span>
<div class="box"></div>
</div>
解决方案
这是一个基于您的代码的基本 jQuery 示例。
$(function() {
$("input").focus(function() {
$(this).parent().addClass("inpFocus");
}).blur(function() {
$(this).parent().removeClass("inpFocus");
});
});
body {
padding: 1rem 2rem;
}
input {
background: transparent;
padding: 1rem;
outline: none;
border: none;
flex: 1;
}
input:hover {
border-color: red;
}
input:focus~.label,
input:not(:focus):valid~.label {
color: #868ca0;
font-weight: 700;
border-color: red;
top: -0.6rem;
font-size: 14px;
background: #fff;
opacity: 1;
}
.label {
position: absolute;
left: 1rem;
top: 1.2rem;
pointer-events: none;
color: #666;
transition: 0.2s ease all;
}
.block {
padding-right: 1rem;
width: 300px;
margin: 1.3rem 0;
border-radius: 6px;
position: relative;
display: flex;
align-items: center;
font-size: 16px;
border: 2px solid #dadada;
}
.box {
height: 30px;
width: 30px;
border-radius: 50%;
background: orange;
}
.inpFocus {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
<input type="text" required/>
<span class="label">Name</span>
</div>
<div class="block">
<input type="password" required/>
<span class="label">Password</span>
<div class="box"></div>
</div>
参考
推荐阅读
- python - 如何使用python在azure中获取虚拟机的资源ID
- python - 如何将 json 有效负载与图像一起发送到 FastAPI 实例?
- css - 将滚动文本的 css 翻译同步到相同的速度(但持续时间不同)
- c - 链表中的整数值有时被设置为 0
- python - tkinter 的 radioButton 似乎丢失了 state="disabled" 的配置
- android - Android:错误:不能从静态上下文引用非静态类型变量 T
- c - 程序中计算C中单词、句子和字母数量的问题
- xsl-fo - 仅在其列中换行的文本 XSL fo
- python - 用泡菜保存变量
- android - 使用 JFrog Artifactory 的 Kotlin 多平台库