最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Scrolling a currently active word into view - Stack Overflow

programmeradmin2浏览0评论

I want to create the search bar like it is in Zepto website. How do I move the current words showing in the search from center to up and the next word should appear from bottom to center.

I tried to render the containers in a single container and bring the words in view with the help of scrollIntoView() method, but it would also displace the span woth "search" keyword in it.

import React, { useEffect, useRef, useState } from "react";

const ShuffelingSearchSuggestions = () => {
  const words = ["mango", "banana", "play station", "headphones", "shoes"];
  const [showInput, setShowInput] = useState(false);
  const [currentWord, setCurrentWord] = useState(words[0]);
  const [search, setSearch] = useState("");
  const searchRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    function handleClickOutside(e) {
      if (searchRef.current && !searchRef.current.contains(e.target)) {
        setShowInput(false);
      }
    }
    window.addEventListener("mousedown", handleClickOutside);

    const intervalId = setInterval(() => {
      setCurrentWord((prev) => {
        const currentIndex = words.indexOf(prev);
        const nextIndex = (currentIndex + 1) % words.length;
        return words[nextIndex];
      });
    }, 2000);

    return () => {
      window.removeEventListener("mousedown", handleClickOutside);
      clearInterval(intervalId);
    };
  }, []);

  function handleFocus() {
    setShowInput(true);
    setTimeout(() => {
      if (inputRef.current) {
        inputRef.current.focus();
      }
    }, 500);
  }

  return (
    <div className="w-full h-[200px] bg-white flex">
      <div
        ref={searchRef}
        tabIndex={0}
        className="bg-gray-300 w-[70%] h-[65px] m-auto rounded-full px-5"
        onFocus={handleFocus}
      >
        <div className="h-full w-full flex items-center text-xl font-medium relative">
          <span className="mr-2">search:</span>
          {!showInput && (
            <span
              className="select-none w-full absolute left-[4rem] transition-opacity duration-400 opacity-100"
              style={{
                opacity: 1,
                transform: "translateY(0px)",
                transition: "opacity 0.4s ease, transform 0.4s ease",
              }}
            >
              "{currentWord}"
            </span>
          )}
          {showInput && (
            <input
              ref={inputRef}
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              type="text"
              className="w-full bg-transparent outline-none z-10"
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default ShuffelingSearchSuggestions;
发布评论

评论列表(0)

  1. 暂无评论