防止select2将下拉列表向上翻转

2021/01/17 00:42 · jquery ·  · 0评论

按照标题,是否有一种方法可以强制select2始终创建一个下拉列表而不是一个下拉列表?

似乎还有一些JavaScript,它们可能会在您在下拉菜单上方滚动时引起翻转,或者添加新的CSS类“ select2-drop-above”,或者两者兼而有之。

编辑:我应该指定要通过select2-rails拉入库。我希望有一种解决方法,不涉及自己提取整个select2库并直接编辑select2.js文件。

正如您提到的,不希望修改插件。我遇到了类似的问题,无法找到使用select2选项来强制下拉列表保持在下面的方法。我最终得到的解决方案如下:

$("#mySelect2").select2({ ...options... })
    .on('select2-open', function() {

        // however much room you determine you need to prevent jumping
        var requireHeight = 600;
        var viewportBottom = $(window).scrollTop() + $(window).height();

        // figure out if we need to make changes
        if (viewportBottom < requireHeight) 
        {           
            // determine how much padding we should add (via marginBottom)
            var marginBottom = requireHeight - viewportBottom;

            // adding padding so we can scroll down
            $(".aLwrElmntOrCntntWrppr").css("marginBottom", marginBottom + "px");

            // animate to just above the select2, now with plenty of room below
            $('html, body').animate({
                scrollTop: $("#mySelect2").offset().top - 10
            }, 1000);
        }
    });

此代码确定是否有足够的空间将下拉菜单放在底部,如果没有,则通过在页面的某些元素上添加margin-bottom来创建下拉菜单。然后滚动到select2的正上方,这样下拉列表就不会翻转。

由于修改源代码不是一种选择,并且向select2:open事件添加一个钩子不是很优雅,尤其是当您在同一页面中有多个select2实例时,我为Select2插件编写了一个小扩展名

我的实现是受尚未合并的插件存储库(https://github.com/select2/select2/pull/4618)中的PR启发的

基本上,以下代码会覆盖处理下拉位置的原始插件功能,并添加一个新选项(dropdownPosition)强制下拉位置在上方/下方。

dropdownPosition选项可以采用以下值:-below下拉菜单始终显示在输入的底部;--above下拉菜单始终显示在输入的顶部;- auto(默认)-它使用旧的行为。

只需在select2.js文件后插入以下代码

(function($) {

  var Defaults = $.fn.select2.amd.require('select2/defaults');

  $.extend(Defaults.defaults, {
    dropdownPosition: 'auto'
  });

  var AttachBody = $.fn.select2.amd.require('select2/dropdown/attachBody');

  var _positionDropdown = AttachBody.prototype._positionDropdown;

  AttachBody.prototype._positionDropdown = function() {

    var $window = $(window);

    var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
    var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');

    var newDirection = null;

    var offset = this.$container.offset();

    offset.bottom = offset.top + this.$container.outerHeight(false);

    var container = {
        height: this.$container.outerHeight(false)
    };

    container.top = offset.top;
    container.bottom = offset.top + container.height;

    var dropdown = {
      height: this.$dropdown.outerHeight(false)
    };

    var viewport = {
      top: $window.scrollTop(),
      bottom: $window.scrollTop() + $window.height()
    };

    var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
    var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);

    var css = {
      left: offset.left,
      top: container.bottom
    };

    // Determine what the parent element is to use for calciulating the offset
    var $offsetParent = this.$dropdownParent;

    // For statically positoned elements, we need to get the element
    // that is determining the offset
    if ($offsetParent.css('position') === 'static') {
      $offsetParent = $offsetParent.offsetParent();
    }

    var parentOffset = $offsetParent.offset();

    css.top -= parentOffset.top
    css.left -= parentOffset.left;

    var dropdownPositionOption = this.options.get('dropdownPosition');

    if (dropdownPositionOption === 'above' || dropdownPositionOption === 'below') {
      newDirection = dropdownPositionOption;
    } else {

      if (!isCurrentlyAbove && !isCurrentlyBelow) {
        newDirection = 'below';
      }

      if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
        newDirection = 'above';
      } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
        newDirection = 'below';
      }

    }

    if (newDirection == 'above' ||
    (isCurrentlyAbove && newDirection !== 'below')) {
        css.top = container.top - parentOffset.top - dropdown.height;
    }

    if (newDirection != null) {
      this.$dropdown
        .removeClass('select2-dropdown--below select2-dropdown--above')
        .addClass('select2-dropdown--' + newDirection);
      this.$container
        .removeClass('select2-container--below select2-container--above')
        .addClass('select2-container--' + newDirection);
    }

    this.$dropdownContainer.css(css);

  };

})(window.jQuery);

初始化插件,如下所示:

$(document).ready(function() {
  $(".select-el").select2({
    dropdownPosition: 'below'
  });
});

在这里提琴:https :
//jsfiddle.net/byxj73ov/

Github存储库:https :
//github.com/andreivictor/select2-dropdownPosition


更新2019年12月30日

摆弄最新的Select2版本(v4.0.12):https :
//jsfiddle.net/g4maj9ox/

您可以只编辑select2.js


说的地方

enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),

只需将其更改为

enoughRoomBelow = true,
enoughRoomAbove = false,

您可以这样覆盖CSS:

.select-dropdown {
  position: static;
}
.select-dropdown .select-dropdown--above {
      margin-top: 336px;
}

我曾经为此找到了一个简单/快速的解决方案:

        $("select").select2({

            // Options

        }).on('select2:open',function(){

            $('.select2-dropdown--above').attr('id','fix');
            $('#fix').removeClass('select2-dropdown--above');
            $('#fix').addClass('select2-dropdown--below');

        });

很简单,您只需打开事件(select2:open)下方.select2-dropdown更改为.select2-dropdown即可

它仅在事件下起作用,并且可以有许多其他方式来执行它,只是在打开选择时更改类。

ps。如果您尝试使用jquery填充选择内容,它将无法正常工作。

更新自[shanabus]答案

jQuery("#line_item").select2({
            formatResult: Invoice.formatLineItem
        })
        .on('select2-open', function() {
            // however much room you determine you need to prevent jumping
            var requireHeight = $("#select2-drop").height()+10;
            var viewportBottom = $(window).height() - $("#line_item").offset().top;

            // figure out if we need to make changes
            if (viewportBottom < requireHeight)
            {
                // determine how much padding we should add (via marginBottom)
                var marginBottom = requireHeight - viewportBottom;

                // adding padding so we can scroll down
                $(".aLwrElmntOrCntntWrppr").css("marginBottom", marginBottom + "px");

                // animate to just above the select2, now with plenty of room below
                $('html, body').animate({
                    scrollTop: $("#select2-drop").offset().top - 10
                }, 1000);
            }
        });
本文地址:http://jquery.askforanswer.com/fangzhiselect2jiangxialaliebiaoxiangshangfanzhuan.html
文章标签: ,   ,   ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!