顶部和左侧坐标不适用于 getBoundingClientRect() - Javascript

Top and Left Coordinates Not Working On getBoundingClientRect() - Javascript

我有一个菜单,我想要一个高亮栏在导航中的菜单项之间转换(这样当您将鼠标悬停在每个菜单项上时,突出显示会从一个菜单项平滑地转到另一个菜单项)。

我可以得到它,所以 'highlight' 改变高度和宽度以匹配 .nav-link 导航项,但我似乎无法使用变换使 X 和 Y 定位坐标工作属性.

任何帮助都会很棒。

艾米丽

代码笔:https://codepen.io/emilychews/pen/QWjOxKz

// SELECT NAV-LINKS AND CREATE A SPAN
var navLinks = document.querySelectorAll(".nav-link"),
  theHighlight = document.createElement("span");
  
// ADD CLASS TO SPAN AND APPEND TO BODY
theHighlight.classList.add("highlight");
document.body.append(theHighlight);

// MOVE THE HIGHLIGHT TO THE NAV LINKS X/Y COORDINATES AND MATCH WIDTH AND HEIGHT
function moveHighlight() {

  var linkCoords = this.getBoundingClientRect();

  var coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top: linkCoords.top + window.scrollY,
    left: linkCoords.left + window.scrollX
  };

  theHighlight.style.width = `${coords.width}px`;
  theHighlight.style.height = `${coords.height}px`;
  theHighlight.style.transform = `translate(${coords.left}px, translate(${coords.top}px)`;
}

// CALL moveHighlight() FUNCTION ON MOUSEENTER
navLinks.forEach(a => a.addEventListener('mouseenter', moveHighlight))
.menu-items {
  display: flex;
  list-style: none;
}

.nav-link {
  margin-left: 2rem;
  display: inline-block;
  position: relative;
}

/* ADDED WITH JAVASCRIPT */
.highlight {
  top: 0;
  left: 0;
  background: red;
  transition: all 0.2s;
  display: block;
  position: absolute;
}
<body>
  <header>
    <nav class="n">
      <ul class="menu-items">
        <li><a class="nav-link" href="#">HOME</a></li>
        <li><a class="nav-link" href="#">WORK</a></li>
        <li><a class="nav-link" href="#">PROCESS</a></li>
        <li><a class="nav-link" href="#">CONTACT</a></li>
      </ul>
    </nav>
  </header>
</body>

您的转换字符串 translate(${coords.left}px, translate(${coords.top}px) 不是有效的 css transform 值。

当用实际值替换变量时,生成的字符串将类似于:translate(80px, translate(16px).

您需要的是:translate(80px, 16px),这意味着您的代码需要:

theHighlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;