jQuery
$('.add-to-cart2').on('click', function () {
var cart = $('.cart');
var imgtodrag = $(this).parent('.item').find("img").eq(0);
if (imgtodrag) {
var imgclone = imgtodrag.clone()
.offset({
top: imgtodrag.offset().top,
left: imgtodrag.offset().left
})
.css({
'opacity': '0.5',
'position': 'absolute',
'height': '150px',
'width': '150px',
'z-index': '100'
})
.appendTo($('body'))
.animate({
'top': cart.offset().top + 10,
'left': cart.offset().left + 10,
'width': 75,
'height': 75
}, 1000, 'easeInOutExpo');
setTimeout(function () {
cart.effect("shake", {
times: 2
}, 200);
}, 1500);
imgclone.animate({
'width': 0,
'height': 0
}, function () {
$(this).detach()
});
}
});
.HTML
<li>
<div class="polaroid item">
<p>
<button class="add-to-cart2" type="button">
Add to cart
</button>
</p>
<img src="/img/rawr.png" alt="item">
</div>
</li>
错误
Uncaught TypeError: Cannot read property 'top' of undefined
嘿
我找到了一个关于如何为购物车部分的物品创建飞行动画的教程,但目前我收到一个错误,告诉我 offset.top 未定义。我试图解决它,发生这种情况的原因是它找不到图像,因此变量"imgtodrag"没有任何可拖动的东西。
如果有人能看到代码中的错误,我会很高兴! :)
你可以在没有parent()
的情况下找到img
:
var imgtodrag = $(".add-to-cart2").find("img").eq(0);
您需要使用closest()
而不是parent()
var imgtodrag = $(this).closest('.item').find("img").eq(0);
因为.item
不是.add-to-cart2
的直接父级,parent()
只在DOM树中向上移动一个级别。所以你需要使用closest()
,它会沿着 DOM 树向上移动,直到找到匹配项。