How to control positioning of jQueryUI datepicker

前端 未结 13 1319
一整个雨季
一整个雨季 2020-12-07 16:55

The datepicker in jQueryUI renders with a dynamic position. It renders according to its css if there\'s enough room for it, but if there isn\'t enough window space it tries

13条回答
  •  -上瘾入骨i
    2020-12-07 17:30

    This is quite an old question however I recently ran into an issue similar to this with the jQuery UI Datepicker. We were already using the solution posted by @JaredC above (specifically this code snippet: $.extend($.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});) however it would not work for a modal that had an input in which we needed to render a dropdown.

    This issue would occur because when scrolling down the page the offset of the input in the modal changes relative to the top of the scrolled page. The resulting behavior would mean that the datepicker would render in a different vertical position depending on how far you scrolled down the page (note: while visible and scrolling the datepicker was already fixed). The solution to this issue ("datepicker input nested within a modal") is to instead calculate the vertical positioning of the input relative to the view screen and then add the height of the input (allowing the "top" css property of the datepicker to be right below that of the input).

    The following snippet is in coffeescript. Instead of returning the regular offset as per @JaredC's solution we instead obtain the elementId of the input from the 'inst' object and then access the object via jquery in order to use it to calculate the input's distance from the top of the screen relative to the viewport.

    # CoffeeScript
    $.extend( $.datepicker, { _checkOffset: (inst,offset,isFixed) ->
            offset.top = $("##{inst.id}").offset().top - $(window).scrollTop() + $("##{inst.id}")[0].getBoundingClientRect().height
            offset
        }
    )
    

    // JavaScript
    $.extend($.datepicker, {
        _checkOffset: function(inst, offset, isFixed) {
            offset.top = $("#" + inst.id).offset().top - $(window).scrollTop() + $("#" + inst.id)[0].getBoundingClientRect().height;
            return offset;
        }
    });
    

提交回复
热议问题