css 为什么当我们把搜索图标放在输入上时,焦点对输入不起作用?

2o7dmzc5  于 2024-01-09  发布在  其他
关注(0)|答案(3)|浏览(132)

这是我的HTML代码:

.search-bar{
     width: 40px;
     height: 45px;
     transition: 0.7s;
}
 .search-icon {
     top: .4%;
     right: 5%;
     width: 35px;
     margin-left: 300px;
     cursor: pointer;
     box-sizing: border-box;
}
 .search-bar:focus{
     cursor: pointer;
     width: 200px;
     outline: none;
}
 .search-btn{
     background-color: transparent;
     outline: none;
     border: none;
     position: absolute;
     top: .4%;
     right: -10%;
     width: 35px;
     height: 35px;
     margin-left: 300px;
     cursor: pointer;
}
 .search-icon:focus ~ .search-bar{
     border-width: 0px;
     width: 200px;
}

个字符
通常,它是一个搜索栏,当我点击输入框或按钮时,它应该将宽度增加到200 px。
问题是我在这个输入中有一个搜索图标,当我点击搜索图标时,宽度不会增加。

92vpleto

92vpleto1#

添加以下规则,当输入或图标被聚焦时增加宽度

.search-bar:focus,
.search-icon:focus ~ .search-bar {
  cursor: pointer;
  width: 200px;
  outline: none;
}

字符串

pb3s4cty

pb3s4cty2#

选择器.search-icon:focus ~ .search-bar不匹配任何东西,因为没有类search-bar的元素是类search-icon的元素的后续兄弟。
相反,您可以考虑在按下.search-icon按钮时使用JavaScript来聚焦<input>元素:

const searchBar = document.querySelector('.search-bar');
document
  .querySelector('.search-icon')
  .addEventListener('click', () => {
    searchBar.focus();
  });
.search-bar {
  width: 40px;
  height: 45px;
  transition: 0.7s;
}

.search-icon {
  top: .4%;
  right: 5%;
  width: 35px;
  margin-left: 300px;
  cursor: pointer;
  box-sizing: border-box;
}

.search-bar:focus {
  cursor: pointer;
  width: 200px;
  outline: none;
}

.search-btn {
  background-color: transparent;
  outline: none;
  border: none;
  position: absolute;
  top: .4%;
  right: -10%;
  width: 35px;
  height: 35px;
  margin-left: 300px;
  cursor: pointer;
}
<div class="mid-header-div">
  <div search-bar-div>
    <input class="search-bar" type="text">
    <button class="search-btn">
        <img class="search-icon" src="https://picsum.photos/35/35" />
      </button>
  </div>
ih99xse1

ih99xse13#

没有办法通过其子元素选择父元素,但是:has伪类就像是通过子元素间接选择父元素。
你应该知道:has,因为最近它有所有浏览器的支持

.search-bar-div{
  display:flex;
  flex-direction:column;
  gap:1rem;
}
.search-bar{
    width: 40px;
    transition: 0.7s;
}

.search-bar:focus{
  width: 200px;
  outline: none;
}

.search-bar:has(+ .search-btn:is(:focus,:hover)){ /*magic is here*/
  width: 200px;
}

.search-btn{
  width: 50px;
}

个字符

相关问题