linche0859
1/13/2020 - 3:51 PM

Follow Along Link Highlightter

      (function() {
        const highLight = document.createElement('span');
        const hypes = document.querySelectorAll('a');
        let rect = null;
        highLight.classList.add('highlight');
        document.body.append(highLight);

        function enterHandler() {
          // 單純給 a 標籤,在 window.resize時,會動態取當前 a 標籤位置
          rect = this;
          setPositionHandler();
        }

        function setPositionHandler() {
          if (!rect) return false;
          const { top, left, width, height } = rect.getBoundingClientRect();
          highLight.style.width = width + 'px';
          highLight.style.height = height + 'px';
          highLight.style.top = top + window.scrollY + 'px';
          highLight.style.left = left + window.scrollX + 'px';
        }

        hypes.forEach(a => a.addEventListener('mouseenter', enterHandler));

        window.addEventListener('resize', setPositionHandler);
      })();