javascript - jQuery offset().top 未定义

标签 javascript jquery html

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);

关于javascript - jQuery offset().top 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30028762/

相关文章:

javascript - Google Apps 脚本中的格式化日期

javascript - 在 TypeScript(Javascript) 中部分隐藏电子邮件地址

jquery - 通过平滑滚动导航到不同页面上的 div

html - WordPress 响应问题

javascript - 这是什么错误?

javascript - 以干净的方式修改(修补) meteor 包 - Meteor

html - 如何在 prestashop 1.7 中使标题变粘

javascript - 如何将 innerHTML 与 createTextNode 一起使用?

javascript - 单击父 Div,隐藏包含 Vimeo Iframe 的叠加层

javascript - 禁用 Taphold 默认事件,跨设备