1

假设我们有这个标记:

<div id="container">
    <ul></ul>
    <ul></ul>
</div>

其中的格式<li>如下:

<ul>
   <li>
     <span class="title">Title of the article</span>
     <span class="date" data-value="[TIMESTAMP]">Pretty Date</span>
   </li>
</ul>

我需要做的是:

  • 如果视口宽度足够大:显示两个列表

  • 如果视口宽度很小:按日期合并两个列表

    变量最小值 = 760; $(window).resize(function(){ var width = $(window).width(); if(width <= min){ merge_lists(); } });

我在弄清楚如何做时遇到了一些麻烦:

function merge_lists(){
     /* shall i run 2 .each function and store it in an array, order by date (how?) and
        regenerate a new list?
      */
}
4

1 回答 1

1

我想你喜欢这样的东西:

HTML:

<div id="container">
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/05/01">2012/05/01</span>
       </li>
    </ul>
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/05/05">2012/05/05</span>
       </li>
    </ul>
    <ul>
        <li>
         <span class="title">Title of the article</span>
         <span class="date" data-value="2012/04/10">2012/04/10</span>
       </li>
    </ul>
</div>

jQuery:

var mainlists = $('#container ul'),
    min = 550;

function merge_lists() {
     if (!$('#container').hasClass('merged')) {
        var temp = mainlists.clone(true),
            lists = $('li', temp);
        lists.sort(function(a, b) {
            var d1 = $('span.date', a).data('value'),
                d2 = $('span.date', b).data('value');
            if (new Date(d1).getTime() > new Date(d2).getTime()) return 1;
        });
        $('#container').empty().append($('<ul>', {
            html: lists
        }));
        $('#container').addClass('merged');
    }
}

function restore_lists() {
    if ($('#container').hasClass('merged')) {
       $('#container').empty().append(mainlists.clone(true));
       $('#container').removeClass('merged');
    }
}

$(window).resize(function() {
    var winWidth = $(window).width(),
        winHeight = $(window).height();
    $('#resolution').html(winWidth + 'px x ' + winHeight + 'px');
    if (winWidth < min) {
        merge_lists();
        $('body').css('background', '#ddd');
    } else {
        restore_lists();
        $('body').css('background', '#fff');
    }
});

演示

于 2012-05-12T15:40:00.030 回答