我正在处理图像源在鼠标悬停在div上时发生更改的脚本。我已经想出了如何通过自己选择图像来更改源代码,但我反而想通过使用.find()在div中选择图像来更改源代码。有什么不工作?使用.find()更改图像上的src jQuery
$(document).ready(function() {
// Declare Arrays
imgList = new Array();
imgList["ref1"] = new Array();
imgList["ref2"] = new Array();
imgList["ref3"] = new Array();
//Set values for each mouse state
imgList["ref1"]["out"] = "http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg";
imgList["ref1"]["over"] = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/European_cat_02.jpg/400px-European_cat_02.jpg";
imgList["ref2"]["out"] = "http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg";
imgList["ref2"]["over"] = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/European_cat_02.jpg/400px-European_cat_02.jpg";
imgList["ref3"]["out"] = "http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg";
imgList["ref3"]["over"] = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/European_cat_02.jpg/400px-European_cat_02.jpg";
//Add the swapping functions
$("div").mouseover(function(){
$(this).find('img').attr("src", imgList[ $(this).attr("id") ]["over"]);
});
$("div").mouseout(function(){
$(this).find('img').attr("src", imgList[ $(this).attr("id") ]["out"]);
});
});
div {
width:100px;
display:inline-block;
}
img {
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg" id="ref1"/>
</div>
<div>
<img src="http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg" id="ref1"/>
</div>
<div>
<img src="http://img-aws.ehowcdn.com/600x600p/photos.demandstudios.com/142/14/fotolia_1230128_XS.jpg" id="ref1"/>
</div>
'imgList'及其所有'ref'元素应该是的目的和不是数组 – Andreas
在我的愚见中,你已经使它复杂化了。我可以为你制作一个更简单的方法吗? –
是的请!添加一件事 - 我想选择div而不是图像本身,因为在img之前会出现一个伪元素,它将出现在mouseover上 – Yvonne