首页 > 解决方案 > 如何保持 CSS 悬停和 jQuery 文本/输入和容器打开?

问题描述

我构建了一个搜索框,它几乎完全按照我的意愿运行,除了一个小问题,只有部分解决方案有效。我已经从这里尝试了一些关于“SO”的答案,甚至从这里得到了一些想法来把它们放在一起,我非常感激,但我现在真的坚持下去了。

在 CSS 悬停后,整个内容从一个很棒的字体图标打开,这包括它所在的“框”和输入。我有一些 jQuery 来保持框打开,直到用户点击离开它,但是如果鼠标移动,即悬停被拿走,那么文本/输入消失(框保持打开状态)。我希望整个搜索框在悬停后保持打开状态,包括文本,以便它保持可见,即使用户将鼠标移开,然后在点击离开时全部关闭(或者当然如果搜索已输入,但那是另一回事)我已经走到了这一步,我知道我一定错过了一些相对较小的东西,所以谢谢你的帮助!此外,如果任何代码出现严重错误或可以改进,我将非常感谢任何输入!

div.search-box:hover > input.search-txt- 这似乎是让我大吃一惊的 CSS 的主要部分。我试过移动悬停等,但 > 似乎没有像我想象的那样工作。我尝试为“文本输入”添加或编写新的 jQuery,类似于保持“框”打开,但这个 CSS 选择器似乎覆盖了它或其他东西。我什至尝试通过 jQuery 自己添加一个类,但它又遇到了同样的问题。如果我不使用这个选择器,那么我或多或少会回到第一方。

我在下面添加了基本代码并制作了一个 jsfiddle。 https://jsfiddle.net/g7vkc3x1/15/#&togetherjs=oRMrQkQlLD

HTML:

<div class="search-head">
                <div class="search-box">
                    <input class="search-txt" type="text" name="" placeholder="Type to search...">
                        <a class="search-btn" href="#">
                            <i class="fas fa-search"></i>
                        </a>
                </div>
            </div>
CSS:
.search-head {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.search-box {
  position: absolute;
  height: 34px;
  min-width: 2.73%;
  transition: width 1s;
  border-radius: 80px;
  padding: 0.3em;
  margin-top: 10px;
  background: rgb(161, 161, 161);
}

div.search-box:hover,
.perm-hover {
  width: 60%;
  background-color: white;
}

div.search-box:hover > input.search-txt { 
  width: 75%;
  padding: 0 6px;
  margin-left: 1.5em;
}

.search-btn {
  color: var(--clr-primary-1);
  float: right;
  width: 3.8em;
  height: 3.7em;
  border-radius: 50%;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.search-btn > i {
  font-size: 2em;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: rgb(0, 112, 177) !important;
  font-size: 2em;
  line-height: 2em;
  width: 0;
  font-weight: bold;
}

jQuery:

{
  $(".search-box").click(function () {
    $(".search-box").addClass("perm-hover");
  });

  $(".search-box").click(function (e) {
    e.stopPropagation();
  });

  $(function () {
    $(document).click(function () {
      $(".search-box").removeClass("perm-hover");
    });
  });
}

标签: htmljquerycss

解决方案


我找到了你的错误,当你将鼠标移开后,你的输入再次隐藏。在这段代码

div.search-box:hover > input.search-txt {
  width: 75%;
  padding: 0 6px;
  margin-left: 1.5em;
}

您应该将其更改为:

div.search-box:hover > input.search-txt, div.search-box.perm-hover > input.search-txt {
  width: 75%;
  padding: 0 6px;
  margin-left: 1.5em;
}

因此,当搜索框(父级)获取 perm-hover 的类时,它应该将 css 扩展为悬停在其中的输入上。


推荐阅读