首页 > 解决方案 > 突出显示元素时更改颜色以链接

问题描述

我正在尝试使此链接突出显示,并希望在鼠标悬停时将链接的颜色更改为黑色,并保持这种状态,直到悬停到另一个链接。我怎样才能做到这一点?(codepen:https ://codepen.io/marioecg/pen/ZMKvKd )

这是 HTML:

<nav>
  <ul class="menu">
    <li><a href="#0">Home</a></li>
    <li><a href="#0">About</a></li>
    <li><a href="#0">Help</a></li>    
    <li><a href="#0">Contact</a></li>
  </ul>
</nav>

<span class="highlight  appear"></span>

这是JavaScript:

// Select all links
const triggers = document.querySelectorAll('a');

// Select highlight element
const highlight = document.querySelector('.highlight');

// Highlight padding values
const paddingTop =  parseInt(window.getComputedStyle(highlight, null).getPropertyValue('padding-top'));
const paddingLeft = parseInt(window.getComputedStyle(highlight, null).getPropertyValue('padding-left'));

// Grab size values of the first link
const initialCoords = triggers[0].getBoundingClientRect();

// Create initial values for highlight making by using the size of the first link
const init = {
  width: initialCoords.width,
  height: initialCoords.height,
  top: initialCoords.top - paddingTop + window.scrollY,
  left: initialCoords.left - paddingLeft + window.scrollX,
}

// Set initial values to highlight element
highlight.style.width = `${init.width}px`;
highlight.style.height = `${init.height}px`;
highlight.style.transform = `translate(${init.left}px, ${init.top}px)`;

// Gets size values of each link and updates position, width and height of highlight element
function highlightLink() {
  const linkCoords = this.getBoundingClientRect();
  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top: linkCoords.top - paddingTop + window.scrollY,
    left: linkCoords.left - paddingLeft + window.scrollX
  }

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

// Runs function where each link is hovered
triggers.forEach(a => a.addEventListener('mouseenter', highlightLink));

标签: javascript

解决方案


为什么不使用 CSS?看看这支笔:HTML

<nav>
  <ul class="menu">
    <li><a href="#0">Home</a></li>
    <li><a href="#0">About</a></li>
    <li><a href="#0">Help</a></li>    
    <li><a href="#0">Contact</a></li>
  </ul>
</nav>

CSS:

a{
  color: blue;
}

a:hover{
  color: red;
}

https://codepen.io/alvaro-alves/pen/vzmjym


推荐阅读