Skip to content

搜索组件跳转

ts
window.addEventListener("DOMContentLoaded", () => {
  const searchBoxList = document.querySelectorAll(
    ".hlx-component-search"
  ) as NodeListOf<HTMLDivElement>;

  searchBoxList.forEach((searchBox) => {
    const searchInput = searchBox.querySelector("input") as HTMLInputElement;
    const searchButton = searchBox.querySelector("button") as HTMLButtonElement;

    if (searchButton) {
      searchButton.addEventListener("click", () => {
        if (searchInput && searchInput.value) {
          const value = searchInput.value;
          console.log(value);
        }

        hlx_to_search_page(searchInput.value);
      });
    }

    if (searchInput) {
      searchInput.addEventListener("keyup", (e) => {
        if (e.key === "Enter") {
          hlx_to_search_page(searchInput.value);
        }
      });
    }
  });

  function hlx_to_search_page(keyword: string) {
    if (!keyword) {
      return alert("搜索关键词不能为空");
    }

    const SEARCH_URL = "/web/column/col5008901.html";

    window.location.href = SEARCH_URL + "?keyword=" + keyword;
  }
});

案例

档案馆

html
<div class="hlx-component-search">
  <input type="text" placeholder="请输入关键词" />
  <button>
    <img src="/assets/images/icon/search.png" />
  </button>
</div>
scss
.hlx-component-search {
  display: flex;
  display: -ms-flexbox;

  align-items: center;
  -ms-flex-align: center;

  width: 100%;
  height: 100%;

  border-radius: 999px;
  background-color: rgba(255, 255, 255, 0.4);

  padding: 0 10px;

  input {
    width: 0;
    flex: 1 0 0;
    -ms-flex: 1 0 0%;

    border: none;
    outline: none;
    background-color: transparent;

    color: #fff;

    &::placeholder {
      color: #fff;
    }
  }

  button {
    height: 30px;
    border: none;
    outline: none;
    background-color: transparent;

    img {
      width: 14px;
      height: 14px;
    }
  }
}