Javascript/jQuery - 搜索编号类,如果未找到类则跳转到最近的编号

标签 javascript jquery

我有一个列表,它代表一天中的某些个小时。就像这样:

<ol>
    <li class="9">Item</li>
    <li class="10">Item</li>
    <li class="11">Item</li>
    <li class="13">Item</li>
    <!-- and so on .... -->
</ol>

我有一个“现在”按钮,它获取当前小时,然后通过动画在列表中查找该小时,如下所示:

$('#jump-to-now').click(function () {
        // new date object
    var date = new Date(),
        // give us the hour
        theHour = date.getHours();

    scrollToHour(theHour);
});

function scrollToHour(hourAsNumber) {
    // use the hour number and match it against a day with a class of that number
    var theListingItem = listingDays.filter('.active-day').find('li').filter('.' + hourAsNumber),
        // get the offset relative to the document
        offsetTop = theListingItem.offset().top;

    $('html, body').animate({
        scrollTop: offsetTop
    }, slideAnimationTime);
}

这里唯一的问题是,如果没有包含该小时类别的列表项,则不会发生任何情况。我想做的是转到当前时间之后最近的时间。

例如,现在是上午 7 点,用户单击按钮,代码发现上午 7 点之后最接近的列表项匹配是上午 9 点,然后跳转到该列表项。

我该怎么做?

最佳答案

大致的逻辑(您可能需要调整):

function scrollToHour(hourAsNumber) {

    var lis = listingDays.filter('.active-day').find('li');

    // use the hour number and match it against a day with a class of that number
    var theListingItem = lis.filter('.' + hourAsNumber);

    // if no item for the specified hour, find nearest
    if(theListingItem.length == 0) {
        var delta = 1;

        while(theListingItem.length == 0 && delta <= lis.length) {
            // check next
            theListingItem = lis.filter('.' + (hourAsNumber + delta) );

            // check previous (uncomment if needed)
            /*
            if(theListingItem.length == 0) {
                theListingItem = lis.filter('.' + (hourAsNumber - delta) );
            }
            */

            delta++;
        }
    }

    // get the offset relative to the document
    var offsetTop = theListingItem.offset().top;

    $('html, body').animate({
        scrollTop: offsetTop
    }, slideAnimationTime);
}

关于Javascript/jQuery - 搜索编号类,如果未找到类则跳转到最近的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597488/

相关文章:

php - 可以在 PHP echo 中自动完成 CSS/Javascript/Jquery?/HTML 的编辑器

javascript - Ractive,&lt;input&gt; 上的两个绑定(bind)

javascript - 从 VBA 到 Javascript 的转换

javascript - jquery mouseenter 不适用于特定 div

javascript - 如何在类组件中使用 setState 以正确的方式更新数组内对象的属性?

javascript - 在javascript中替换多个字符

javascript - Jquery:如何 sleep 或延迟?

jquery - 如果文本框具有焦点,则按下 Enter 键时执行功能

jQuery 旋转 div onclick +/-90

javascript - 从 AJAX GET 获取 HTML 值