javascript - 突出显示元素时更改颜色以链接
问题描述
我正在尝试使此链接突出显示,并希望在鼠标悬停时将链接的颜色更改为黑色,并保持这种状态,直到悬停到另一个链接。我怎样才能做到这一点?(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));
解决方案
为什么不使用 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;
}
推荐阅读
- python - 使用多级 groupby 在 python 中创建一个新列
- python - 通过变量连接字符串和数字。抛出这个“TypeError:必须是 str,而不是 int”
- javascript - 使用 JS 创建用户屏幕截图并通过 ajax 问题发送到服务器
- python - 使用 Jupyter 重绘 matplotlib.pyplot.imshow
- python - Seaborn 以错误的方式生成图表
- javascript - Javascript 语法对齐 (moment.js)
- oracle - Oracle 中的光标与 FOR 循环
- java - 是否可以以编程方式确定是否使用 W3C 动作命令?
- android - Android - 矢量绘图可以存储 GIF 文件/动画图像吗?
- c# - 将对象的实例传递给以 Action<> 作为参数的方法