防止select2向上翻转下拉列表 [英] Prevent select2 from flipping the dropdown upward
问题描述
根据标题,有没有办法强制select2总是创建一个下拉,而不是一个下拉?
As per title, is there a way to force select2 to always create a dropdown instead of a drop-up?
还有一些javascript是或者在滚动到下拉列表上方时触发翻转,添加一个新的CSS类select2-drop-above或两者。
There also appears to be some javascript that is either causing the flip when you scroll above the dropdown, adding a new CSS class "select2-drop-above", or both.
编辑:我应该指定我通过select2-rails拉库。我希望有一个方法,这不涉及拉整个select2 lib在自己和直接编辑select2.js文件。
I should've specified that I'm pulling the library in via select2-rails. I'm hoping there is a way around this that doesn't involve pulling the whole select2 lib in myself and editing the select2.js file directly.
推荐答案
修改插件不是首选,因为你提到。我有一个类似的问题,没有找到一个方法使用 select2
选项强制下拉保持低于。我最终得到的解决方案如下:
Modifying the plugin is not preferred as you mention. I had a similar issue and couldn't find an way to use select2
options to force the dropdown to stay below. The solution I ended up with is the following:
$("#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上方,使下拉菜单不会翻转。
This code determines if there is enough room to place the dropdown at the bottom and if not, creates it by adding margin-bottom to some element on the page. It then scrolls to just above the select2 so that the dropdown won't flip.
这篇关于防止select2向上翻转下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!