iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
JavaScript

React30——用 React 探索 JavaScript30 的魅力系列 第 22

[Day22]_Follow-Along-Link-Highlighter

  • 分享至 

  • xImage
  •  

Day22 要來做的是可以根據滑鼠滑過去就出現背景色的螢光筆

資料

  const [highlightStyle, setHighlightStyle] = useState<HighlightStyle>({
    transform: "translateX(0px) translateY(0px)",
    width: "0px",
    height: "0px",
  });

滑鼠動作

  const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {
    const linkCoords = e.currentTarget.getBoundingClientRect();
    const coords = {
      width: linkCoords.width + 2,
      height: linkCoords.height + 2,
      top: linkCoords.top + window.scrollY,
      left: linkCoords.left + window.scrollX,
    };

    setHighlightStyle({
      width: `${coords.width}px`,
      height: `${coords.height}px`,
      transform: `translateX(${coords.left}px) translateY(${coords.top}px)`,
    });
  }, []);

連結元件

  const Link: React.FC<LinkProps> = ({ href, children }) => (
    <a
      href={href}
      className="relative text-blue-600 hover:text-blue-800 z-10"
      onMouseEnter={handleMouseEnter}
    >
      {children}
    </a>
  );

畫面結構

  return (
    <div className="p-4">
      <div
        className="fixed top-0 left-0 bg-yellow-300 opacity-50 transition-all duration-200 ease-in-out pointer-events-none rounded-md"
        style={highlightStyle}
      />
      <nav className="flex justify-around mb-4">
        <Link href="#">Home</Link>
        <Link href="#">About</Link>
        <Link href="#">Contact</Link>
      </nav>

      <p className="mt-4">
        This is some text with a <Link href="#">link</Link> in it.
      </p>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/tyjwrd


上一篇
[Day21]_Geolocation
下一篇
[Day23]_Speech-Synthesis
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言