Check if element is before or after another element in jQuery

后端 未结 9 1607
花落未央
花落未央 2020-12-23 16:23

Let us suppose I have this markup

First

Hi

Hello

Second

9条回答
  •  余生分开走
    2020-12-23 16:45

    The previous answers work fine IF the elements in question are siblings (which they are in the original question) but a more general solution would consider the following scenario:

    First

    Hi

    Hello

    Second

    Bye

    Goodbye

    A more general solution would be:

    $.extend($.fn, {
        isBefore: function(sel, context) {
            // Get all element within the context.
            var all = $(context || document).find("*");
            return all.index(this[0]) < all.index($(sel));
        },
    
        isAfter: function(sel, context) {
            return !this.isBefore(sel, context);
        }
    });
    

    Where "context" is an optional parameter that merely limits the search area for jQuery to improve performance. I haven't performed any tests but "context" is probably unnecessary since $("*") seems to execute qualitatively fast. Also note that index() will return -1 is either element is not within the context.

    $("#first").isBefore("#second");  
    // Gives the same result as
    $("#first").isBefore("#second", "#top");
    

    Of course this all assumes that by "before" and "after" you mean their order in the document model. If you are concerned about their relative positions on the display you would want to examine the elements display coordinates relative to the document as "relative", "fixed" and "absolute" CSS positions make anything possible.

提交回复
热议问题