我如何使用 jQuery 将鼠标悬停在 div 中的图像更改为另一个图像?我有一个 div,其中包含图像、标题和一些文本。我想在鼠标悬停时更改图像。
我使用的模板也使用了很多 jquery,但文件到处都是。我应该把函数放在哪里?
编辑:这是我目前的代码:
CSS:
#tour {
overflow:hidden;
width:100%;
padding:56px 0 47px
}
#tour #link {
height:auto;
width:200px; /* 140px + 60px */
float:left;
margin-right:25px;
margin-left:10px;
}
#tour #link:hover {
cursor:pointer;
}
#tour img {
/* Float the image to the left of text */
width:50px;
float: left;
margin-right:10px;
height:auto;
}
#tour h1, h2, h3, h4 {
display:block;
width:140px;
float:left;
}
#tour p, #tour p.last {
display:table-row;
width:140px;
alignment-baseline:baseline;
/* Custom added */
color: #333;
font-size: 10px;
margin: 5px;
font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif;
font-size: 11px;
width: 140px;
}
HTML:
<div id="tour">
<div id="link" onclick="location.href='#';" >
<img src="images/icn1.png" alt="" />
<h2>Pitch</h2>
<p>Present your ideas in a manner that will leave your customers in amazement.</p>
</div>
</div>
最佳答案
$('div#imageContainer').on('mouseover', function(){
$(this).children('img').attr('src','../newImage.png');
});
这样就可以了。将代码放在哪里并不重要,只要它在 $(document).load(function(){...});
注意:这是使用最新的 jQuery 1.7.1 .on()
函数,这是这个版本的新功能。同样的事情可以用 .bind()
评论更新:
如果你想把这个函数放在一个单独的文件中,你可以把它包装在一个函数中
function imageSwap(){
$('div#imageContainer').on('mouseover', function(){
$(this).children('img').attr('src','../newImage.png');
});
}
然后只需在文档加载中调用 imageSwap()
函数即可。
此外,如果您想在具有不同图像的多个 div 上使用它,您可以执行以下两项操作之一。 A) 将图像命名为 img1_over.png
和 img1.png
,在这种情况下,您可以这样修改代码:
$('div#imageContainer').on('mouseover', function(){
var img = $(this).children('img');
img.attr('src', img.attr('src').replace('.png', '_over.png'));
});
或者您可以将图像路径存储在图像本身的数据属性中。在您的 HTML 中,您可以将悬停图像添加到数据属性中,如下所示:
<img src="../cool_img.png" data-hover="../ever_cooler_image.png" />
你的代码应该是这样的:
$('div#imageContainer').on('mouseover', function(){
var img = $(this).children('img');
img.attr('src', img.data('hover'));
});
关于javascript - 将鼠标悬停在 div 内的图像更改为另一个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717785/