gpt4 book ai didi

javascript - 当元素突出显示时更改链接的颜色

转载 作者:行者123 更新时间:2023-12-01 01:43:31 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于javascript - 当元素突出显示时更改链接的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com