javascript - 按住键后 Jquery/JS : skip N items from siblings. 错误

标签 javascript jquery html css node.js

当我在 div 类中有一个 div 列表时。

<div class="list-group games">
   <div>item</div>
    <div>item</div>
    <div>item</div>
    <div>item</div>
    <div class="active">item</div>
    <div>item</div>
    <div>item</div>
</div>

这是一个包含 700 个元素的非常长的列表,我想使用向下/向上翻页按钮和箭头键向上/向下移动 1 个元素来轻松导航。

它们用于移动单个元素的功能很好。 pgdown/up 功能在按下时也可以使用,中间有一个小的停顿。当我按住 pgdown/up 按钮时,它在执行该功能大约 10 次后开始给我以下错误。

我用过的函数

function pgDown(e){
                e.preventDefault();
                var currentItem = $(".active");
                var itemCount = $(".games").children().length;
                nextItem = currentItem.prevAll().size() - 10;
                if (nextItem < itemCount){
                    currentItem.removeClass('active');
                    currentItem = $(".games div:nth-child("+ nextItem +")").addClass('active');
                    animatedScrollTo(
                        document.body,
                        ($(".active").offset().top) - ($(window).height()/2), 
                        0
                    );
                }
            }

错误:

Uncaught TypeError: Cannot read property 'top' of undefined

它来自函数中的这一行代码

($(".active").offset().top) - ($(window).height()/2), 

有谁知道如何防止这种情况发生?

如果有其他方法可以实现这个目标,那么我很乐意实现它。

最佳答案

似乎在某些时候没有具有“事件”类的元素或者它被隐藏了。 你应该调查一下。 但是,这应该可以防止错误发生:

var activeOffset = $(".active").offset();

if(activeOffset) {
    animatedScrollTo(
      document.body,
      (activeOffset.top) - ($(window).height()/2), 
      0
   ); 
}

关于javascript - 按住键后 Jquery/JS : skip N items from siblings. 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33608406/

相关文章:

javascript - 解析图表 js laravel Blade 中的数组

javascript - 文档高度占原始高度的百分比

javascript - React 和 Meteor "Uncaught TypeError: Cannot read property ' createElement' of undefined"

javascript - jQuery 延迟 : Speeding up queue?

html - 如何固定图像右侧图标的位置

javascript - Win8 Metro-JS 应用程序可以截取自己的屏幕截图吗?

jquery - fullpage.js 导致 nprogress 和其他 JavaScript 问题

javascript - 如何调用 click( ) 属性?

html - 将标题属性添加到 jsf panelGroup?

html - 输入类型编号始终显示 2 位小数