gpt4 book ai didi

javascript - 将鼠标悬停在标签类上更改不同元素中 img 的图像 src

转载 作者:行者123 更新时间:2023-11-28 18:59:46 24 4
gpt4 key购买 nike

假设我有这样的东西:

<div class="right">
<article class="left_image">
<img src="images/coolestimageontheplanet.jpg" class="image_left">
</article>

然后我有一个 UL 列表:

    <ul class="LISTS">
<li><a href="#link" target="_blank" class="hov5">Link 1</a></li>
<!-- etc -->
</ul>

我将在上面的标记方式中列出大约 10 个列表项。基于悬停类,我想交换与 class="image_left" 关联的图像源,如上所示。因此,将鼠标悬停在 class="hov5" 上,您将获得 hov5 图像

最佳答案

您可以为 mouseover 和 mouseleave 添加事件监听器,然后相应地更改 image.src,就像这样

window.addEventListener('load', function() {
function initImageHover(selector, displaySelector) {
var imageContainer = document.querySelectorAll(displaySelector)[0],
elements = document.querySelectorAll(selector);

for (var i = 0, len = elements.length; i < len; i++) {
createHover(elements[i], imageContainer, imageContainer.src);
};
}

function createHover(that, targetElement, originalImage) {

that.addEventListener('mouseover', function() {
var src = that.getAttribute('data-src');
if (src) {
targetElement.src = src;
}
});
that.addEventListener('mouseleave', function() {
targetElement.src = originalImage;
});
}

initImageHover('li > a', '.image_left');
});
<div class="right">
<article class="left_image">
<img src="images/coolestimageontheplanet.jpg" class="image_left">
</article>

<ul class="LISTS">
<li><a href="#link" target="_blank" class="hov1">Link 1</a>
</li>
<li><a href="#link" target="_blank" class="hov2">Link 2</a>
</li>
<li><a href="#link" target="_blank" class="hov3">Link 3</a>
</li>
<li><a href="#link" target="_blank" class="hov4">Link 4</a>
</li>
<li><a href="#link" target="_blank" class="hov5">Link 5</a>
</li>
<li><a href="#link" target="_blank" class="hov6">Link 6</a>
</li>
<li><a href="#link" target="_blank" data-src="http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59" class="hov7">Link 7</a>
</li>
</ul>

关于javascript - 将鼠标悬停在标签类上更改不同元素中 img 的图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832112/

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