gpt4 book ai didi

javascript - HTML + JavaScript : How to change image source on li hover?

转载 作者:行者123 更新时间:2023-11-28 07:31:56 31 4
gpt4 key购买 nike

我有一个 ul,里面有 5 个 li,这个 ul 在 6 的范围内:

<div class="coffee-span-6 recent-news-list">
<ul class="unorder-list news-item-list">
<li class="news-item"><a href="#">Lorem Ipsum</a></li>
<li class="news-item"><a href="#">Lorem Ipsum</a></li>
<li class="news-item"><a href="#">Lorem Ipsum</a></li>
<li class="news-item"><a href="#">Lorem Ipsum</a></li>
<li class="news-item"><a href="#">Lorem Ipsum</a></li>
</ul>
</div>

然后是另一个 span 6 和一张图片:

<div class="coffee-span-6 recent-news-col">
<img id="image" src="http://lorempixel.com/460/200/abstract/1"
</div>

我希望它是这样的,当我将鼠标悬停在第一个 li 上时,它会更改图像源,然后在悬停时恢复为原始图像。我试过这个:

<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();"> <-- this is first li

对于脚本:

<script>
function changeImage(){
document.getElementById("image").src="http://lorempixel.com/460/200/abstract/2";
}
function revertImage(){
document.getElementById("image").src="http://lorempixel.com/460/200/abstract/1";
}

我的意思是,它可以工作,但是如果我在其他 li 上实现 onmouseover 和 onmouseout:

<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();">
<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();">
<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();">
<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();">
<li class="news-item" onmouseover="changeImage();" onmouseout="revertImage();">

我想根据 li 改变图像depending,我该怎么做??我不认为让每个 li 都有不同的方法是非常有效的...有没有办法用更多的 JavaScript 或者 JQuery 来做到这一点?

最佳答案

通过参数将图像的 url 传递给您的函数:

<li class="news-item" onmouseover="changeImage('http://foo.com/img1.jpg');" onmouseout="revertImage('http://foo.com/imgBase.jpg');">
<li class="news-item" onmouseover="changeImage('http://foo.com/img2.jpg');" onmouseout="revertImage('http://foo.com/imgBase.jpg');">
<li class="news-item" onmouseover="changeImage('http://foo.com/img3.jpg');" onmouseout="revertImage('http://foo.com/imgBase.jpg');">
<li class="news-item" onmouseover="changeImage('http://foo.com/img4.jpg');" onmouseout="revertImage('http://foo.com/imgBase.jpg');">
<li class="news-item" onmouseover="changeImage('http://foo.com/img5.jpg');" onmouseout="revertImage('http://foo.com/imgBase.jpg');">

然后:

  function changeImage(imgSrc){
document.getElementById("image").src=imgSrc;
}
function revertImage(imgSrc){
document.getElementById("image").src=imgSrc;
}

关于javascript - HTML + JavaScript : How to change image source on li hover?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31457652/

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