简体   繁体   English

想要在悬停时更改img src,然后在单击时更改为其他src

[英]Want to change an img src on hover, then to a different src on click

I have a div which contains an img - I want to be able to have the img src change on hover (and then back again when not hovered), but also have the same img change to a different src altogether when it is clicked (and then back again upon second click). 我有一个包含img的div-我希望能够在悬停时更改img src(然后在未悬停时再次返回),但是在单击时将相同的img更改完全更改为另一个src(并且然后再次点击返回)。 So far I have the J-Query code to make it change on hover: 到目前为止,我已经有了J-Query代码可以在悬停时对其进行更改:

HTML 的HTML

<div class="tab_box">
   <img id="img1" src="tab.png">
</div>

J-QUERY J查询

$(document).ready(function(){$('#img1').hover(function(){$(this).attr('src','tabt2.png')},function()
{$(this).attr('src','tab.png')}) });

But I am unsure how to then make the change to a different src altogether if clicked (as the image will have to be being hovered over to click it!) Can anyone suggest? 但是我不确定如果单击该按钮后如何将其完全更改为其他src(因为必须将鼠标悬停在该图像上才能单击它!)有人可以建议吗? For various re-sizing reasons, I want to keep the image as a stand alone image within the div, instead of having it as a background-image of the div, if possible 由于各种调整大小的原因,我希望将图像保留为div中的独立图像,而不是尽可能将其作为div的背景图像

You can use the .hover() and .click() functions of Jquery. 您可以使用Jquery的.hover()和.click()函数。 What you have used has syntax problems 您使用的内容存在语法问题

Here is the correct code: 这是正确的代码:

$('#img1').hover(function () {
    $(this).attr('src', 'http://www.fateheducation.com/fatehnew/Testimonial_Image/avatar-small.png');
});
$('#img1').click(function () {
    $(this).attr('src', 'http://moduleoff.com/sites/all/themes/moduleoff/images/xdruplicon_rotated_small.png.pagespeed.ic.Xl8nCuL4lR.png')
});

Working Fiddle 工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM