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

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

这是我的HTML代码:

  1. .search-bar{
  2. width: 40px;
  3. height: 45px;
  4. transition: 0.7s;
  5. }
  6. .search-icon {
  7. top: .4%;
  8. right: 5%;
  9. width: 35px;
  10. margin-left: 300px;
  11. cursor: pointer;
  12. box-sizing: border-box;
  13. }
  14. .search-bar:focus{
  15. cursor: pointer;
  16. width: 200px;
  17. outline: none;
  18. }
  19. .search-btn{
  20. background-color: transparent;
  21. outline: none;
  22. border: none;
  23. position: absolute;
  24. top: .4%;
  25. right: -10%;
  26. width: 35px;
  27. height: 35px;
  28. margin-left: 300px;
  29. cursor: pointer;
  30. }
  31. .search-icon:focus ~ .search-bar{
  32. border-width: 0px;
  33. width: 200px;
  34. }

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

92vpleto

92vpleto1#

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

  1. .search-bar:focus,
  2. .search-icon:focus ~ .search-bar {
  3. cursor: pointer;
  4. width: 200px;
  5. outline: none;
  6. }

字符串

pb3s4cty

pb3s4cty2#

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

  1. const searchBar = document.querySelector('.search-bar');
  2. document
  3. .querySelector('.search-icon')
  4. .addEventListener('click', () => {
  5. searchBar.focus();
  6. });
  1. .search-bar {
  2. width: 40px;
  3. height: 45px;
  4. transition: 0.7s;
  5. }
  6. .search-icon {
  7. top: .4%;
  8. right: 5%;
  9. width: 35px;
  10. margin-left: 300px;
  11. cursor: pointer;
  12. box-sizing: border-box;
  13. }
  14. .search-bar:focus {
  15. cursor: pointer;
  16. width: 200px;
  17. outline: none;
  18. }
  19. .search-btn {
  20. background-color: transparent;
  21. outline: none;
  22. border: none;
  23. position: absolute;
  24. top: .4%;
  25. right: -10%;
  26. width: 35px;
  27. height: 35px;
  28. margin-left: 300px;
  29. cursor: pointer;
  30. }
  1. <div class="mid-header-div">
  2. <div search-bar-div>
  3. <input class="search-bar" type="text">
  4. <button class="search-btn">
  5. <img class="search-icon" src="https://picsum.photos/35/35" />
  6. </button>
  7. </div>
展开查看全部
ih99xse1

ih99xse13#

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

  1. .search-bar-div{
  2. display:flex;
  3. flex-direction:column;
  4. gap:1rem;
  5. }
  6. .search-bar{
  7. width: 40px;
  8. transition: 0.7s;
  9. }
  10. .search-bar:focus{
  11. width: 200px;
  12. outline: none;
  13. }
  14. .search-bar:has(+ .search-btn:is(:focus,:hover)){ /*magic is here*/
  15. width: 200px;
  16. }
  17. .search-btn{
  18. width: 50px;
  19. }

个字符

展开查看全部

相关问题