【问题标题】:Change border color of parent div if child input is focused - TailwindCSS如果聚焦子输入,则更改父 div 的边框颜色 - TailwindCSS
【发布时间】:2022-11-28 19:29:57
【问题描述】:
我知道 TailwindCSS 有类 group 可以使用,但它仅用于在父元素激活某个事件时更改子元素的样式,但我希望它反之亦然。
<div class="parent"> <!-- border color should be red when child is focused -->
<img class="icon">
<input class="child" type="text">
</div>
而且我不想重新编写 css 类。只需使用 TailwindCSS。
【问题讨论】:
标签:
html
css
tailwind-css
【解决方案1】:
使用focus-within变体
<!-- border will be red when input focuesd -->
<div class="focus-within:border-red-500 border">
<img class="icon">
<input class="" type="text">
</div>
DEMO
【解决方案2】:
您可以为此使用 JavaScript。我假设您的输入是通过点击获得焦点的。您可以捕获点击参数并将一个类添加到父级。
<input class="child" type="text" onclick="focusFunction()">
<script>
function focusFunction() {
document.getElementByClass("parent").classList.add("focusclass");
}
</script>
每次单击输入时,都会调用您的focusFuncition。此函数搜索 parent 类并将 focusclass 添加到类属性中。当然你可以改变类的命名。
如果您不止一次使用parent类,也许您必须给您的父母一个唯一的ID才能使用getElementByID而不是类来选择它。