我有一个产品图片列表,每个产品上都有两个不同的图片。第一个显示何时未将鼠标悬停在图像上,第二个显示何时将鼠标悬停在图像上。
问题是,如果我从一个产品图像上悬停并快速转到另一个产品图像,那么第一个产品图像会得到第二个产品的第一个图像,所以是错误的产品图像。
代码如下所示:
.HTML:
<div id="listing">
<ul>
<li data-artnr="3212" class="product">
<div class="image">
<a href="/">
<img src="/pathTo/image/3212.jpg" class="loaded">
</a>
</div>
</li>
<li data-artnr="3213" class="product">
<div class="image">
<a href="/">
<img src="/pathTo/image/3213.jpg" class="loaded">
</a>
</div>
</li>
<li data-artnr="3214" class="product">
<div class="image">
<a href="/">
<img src="/pathTo/image/3214.jpg" class="loaded">
</a>
</div>
</li>
</ul>
</div>
j查询:
$("#listingContent").find(".product").hover(function () {
$product = $(this);
$image = $(this).find(".loaded");
var artnr = $product.data("artnr");
window.oldImage = $image.attr("src");
var newImage = "/pathTo/image/"+artnr+"_topoffer.jpg";
$product.data("old", oldImage);
$image.fadeOut(150, function () {
$(this).load(function () {
$(this).fadeIn(150);
}).attr("src", newImage);
});
},
function () {
$image.fadeOut(150, function () {
$(this).load(function () {
$(this).fadeIn(150);
}).attr("src", oldImage);
});
});
我想这与淡入/淡出有关,因此 $(this) 在淡入开始之前已经更改。有没有更好的方法来避免这个问题?当我删除淡入/淡出时不会出现问题,但这是我想要的东西,因为没有它,传输是很难的。
首先请注意,您的 HTML 无效。 li
元素只能是ul
的子元素,不能是div
的子元素。
问题的原因是因为您使用了全局oldImage
变量。最好使用存储在.product
元素上的"old"data
属性,以便在元素之间快速悬停时没有争用条件。另请注意,您不需要在每个mouseenter
/mouseleave
上重新绑定load()
事件。您可以将其单独放置在所有必需的元素上。试试这个:
$('#listingContent .product .loaded').load(function() {
$(this).fadeIn(150);
});
$("#listingContent .product").hover(function() {
var $product = $(this);
var $image = $product.find(".loaded");
var artnr = $product.data("artnr");
$product.data("old", $image.attr('src'));
$image.fadeOut(150, function() {
$(this).attr("src", "/pathTo/image/" + artnr + "_topoffer.jpg");
});
}, function() {
var $product = $(this);
var $image = $product.find(".loaded");
$image.fadeOut(150, function() {
$(this).attr("src", $product.data('old'));
});
});
而不是做
window.oldImage = $image.attr("src");
您应该将 oldImage 存储在元素本身中,即在某个属性中。
$product.data("old", $image.attr("src"));