【问题标题】:Focus on multiple elements with their properties关注多个元素及其属性
【发布时间】:2019-06-08 15:13:19
【问题描述】:

给出以下 HTML 和 CSS 代码:

input[type=text] {
  background-color: red;
}

input[type=text]:focus {
  background-color: white;
}

button[type=submit] {
  background-color: blue;
}

button[type=submit]:focus {
  background-color: green;
}
<form method="get" id="searchform" action="index.php">
  <input type="text" placeholder="Search..." name="s" id="s" value="" autocomplete="off">
  <button class="search-button" type="submit">
    <span class="icon-search2"></span>
    </button>
</form>

当我专注于 input[type=text] 时,如何激活“button[type=submit]:focus”? 我试图做类似的事情:

input[type=text]:focus {
    background-color: white;
}
button[type=submit]:focus {
    background-color: green;
}

但它不起作用......有什么想法吗?提前致谢!

【问题讨论】:

  • 你能扔codepen吗?

标签: html css focus onfocus


【解决方案1】:

如果没有预处理器,你不能像这样嵌套 CSS。

您想要的是在输入聚焦时选择下一个按钮元素。你可以使用~ selector:

input[type=text] {
  background-color: red;
}

input[type=text]:focus {
  background-color: white;
}

button[type=submit] {
  background-color: blue;
}

button[type=submit]:focus,
input[type=text]:focus~button[type=submit] {
  background-color: green;
}
<form method="get" id="searchform" action="index.php">
  <input type="text" placeholder="Search..." name="s" id="s" value="" autocomplete="off">
  <button class="search-button" type="submit">
      <span class="icon-search2">Click me</span>
    </button>
</form>

【讨论】:

  • 我也会这样写。很好的解决方案。
  • 喜欢这个答案。谢谢!
【解决方案2】:

很简单:你不能。您一次只能关注一个元素。

Source

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 2020-12-24
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2021-10-27
    相关资源
    最近更新 更多