0

我有一个系统警报列表,其中包含与之相关的日期和时间。日期仅在日期发生变化时显示。我想要的是让最上面的日期保持在顶部,#shell直到另一个日期取代它。这与联系人应用程序在 iPhone 上的工作方式非常相似。

我已经设置了一个 jsFiddle,其中包含必要的 jQuery 代码。如果有人可以在这里帮助我,我将非常感激 - 我目前不知道从哪里开始!

HTML 片段:

<div id="shell">
    <div id="alertList">
        <div id="alert_0" class="alert">
            <span class="date">22 Nov, 2012</span>
            <span class="time">02:28</span>
            System alert happened
        </div>
    </div>
</div>

jQuery代码

$("#shell").scroll(function() {
    //This is where the code would be to lock (or alter the margin-top) of the
    //date would be in order to keep it locked to the top
});​
4

2 回答 2

2

试试这段代码……它仍然需要一些工作和重构,但我希望你能理解。(这里也是jsFiddle的链接)

var currentElemIndex = 0;
var currentElem = $('#alertList .date:eq(' + currentElemIndex + ')');
var currentElemMarginTop = parseInt(currentElem.css('margin-top'));
var currentElemHeight = currentElem.outerHeight();
var currentElemPosTop = currentElem.position().top;
var nextElem = $('#alertList .date:eq(' + currentElemIndex+1 + ')');
$('#shell').scroll(function (ev) {
    var scrollTop = $('#shell').scrollTop();
    if (scrollTop >= nextElem.position().top - currentElemHeight) {
        currentElemIndex++;
        currentElem.css('margin-top', currentElemMarginTop + 'px');
        currentElem = nextElem;
        currentElemMarginTop = parseInt(currentElem.css('margin-top'));
        currentElemHeight = currentElem.outerHeight();
        currentElemPosTop = currentElem.position().top;
        nextElem = $('#alertList .date:eq(' + currentElemIndex + ')');
    }
    if (scrollTop  > currentElem.position().top) {
        currentElem.css('margin-top', $('#shell').scrollTop() - currentElem.position().top + 'px');
    }
    if (scrollTop < currentElemPosTop) {
        nextElem = currentElem;
        currentElemIndex--;
        currentElem = $('#alertList .date:eq(' + currentElemIndex + ')');
    }
});
于 2012-11-23T13:19:35.427 回答
1

迟到但确定:jsfiddle

$("#shell").scroll(function() {
    // 21 is because of border and padding.
    var firstVisible = parseInt($("#shell").scrollTop() / ($("#shell .alert:first").height() + 21)),
        firstVisibleElem = $("#shell .alert:eq(" + firstVisible + ")"),
        date = firstVisibleElem.data("date");

    if (date != undefined && date != null && date > -1)
        $("#date_" + date).prependTo(firstVisibleElem);
});

// Save the date corresponding to each alert:
var i = -1;
$("#shell .alert").each(function() {
    var date = $(this).find(".date");
    if (date.length > 0) {
        i++;
        date.attr("id", "date_" + i);
    }
    if (i > -1) {
        $(this).data("date", i);
    }
});
于 2012-11-23T13:19:08.703 回答