突出显示元素时更改颜色以链接

时间:2018-09-03 20:52:09

标签: javascript

我正在尝试使链接突出显示,并希望将鼠标悬停在链接上时将其颜色更改为黑色,并一直保持这种状态,直到将其悬停在另一个链接上为止。我该如何实现? (代码笔: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));

2 个答案:

答案 0 :(得分:1)

为什么不使用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

答案 1 :(得分:1)

One way,您可以通过在链接上添加类后将其添加到链接上,然后在将其链接到另一个链接上时将其删除来实现此效果。

Another way将使用CSS属性mix-blend-mode: difference;: 。 我发现,如果不同时添加will-change: opacity;,使用这种方法看起来也不太流畅。