【问题标题】:Changing div background color when focusing on an input inside it [duplicate]专注于其中的输入时更改div背景颜色[重复]
【发布时间】:2021-09-01 04:20:43
【问题描述】:

您好,我正在尝试通过单击其中的输入来更改 div 的样式。这是我的 HTML:

<li class="search-bar">
  <form action="" class="search-bar">
    <button class="search-btn">
      <i class="fas fa-search"></i>
    </button>
    <input placeholder="Search term..." type="text" />
  </form>
</li>

SCSS:

.search-btn,
input {
    background: transparent;
}

.search-bar {
    background: $light-grey;
    &:hover {
        background: $light-grey-hover;
    }
    &:focus {
        background: white;
    }
}

点击输入时,.search-bar 背景颜色不会改变。我想这是因为我实际上专注于其中的输入,而不是 .search-bar div。

我怎样才能使它在专注于输入时可以更改包含它的整个 div 的样式?这可以使用 css 吗?我应该使用 js 文件吗?

【问题讨论】:

  • 您无法从子级中选择包装器(父级)。但是您可以选择您的兄弟姐妹并实现您的期望
  • 酷。我怎样才能让兄弟姐妹对其中一个发生的事情做出反应?
  • @termani 这不是重复的,不需要父选择器(最初是重复的)..:focus-within自己回答问题,不会混淆;)跨度>
  • @TemaniAfif oups,我之前的评论伤害了你的伪(可能还有更准确的重复)

标签: css input focus background-color


【解决方案1】:

你可能可以使用:focus-within:

.search-bar {
  background: blue;
}

.search-bar:focus-within {
  background: green;
  /* and any style you want to reset */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
<li class="search-bar">
  <form action="" class="search-bar">
    <button class="search-btn">
      <i class="fas fa-search"></i>
    </button>
    <input placeholder="Search term..." type="text" />
  </form>
</li>

【讨论】:

  • 这将在关注内部的任何元素时触发,而不仅仅是输入。
  • @vanowm 确实,只是任何可聚焦的元素。这是为了显示你在哪里;)
猜你喜欢
  • 2021-08-27
  • 2021-03-07
  • 2017-01-16
  • 2022-12-18
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多