gpt4 book ai didi

javascript - 用 Dropup 替换 Bootstrap Dropdown(两个几乎相同的实现的不同事件)

转载 作者:太空狗 更新时间:2023-10-29 14:57:11 25 4
gpt4 key购买 nike

我正在 github pages 上做一个元素,如果 div 的 overflow-y: scroll,我用 .dropup 替换 Bootstrap .dropdown 将导致下拉菜单被 chop/溢出。您可以在此 jsfiddle 看到该功能正常工作.请注意,如果您单击顶行右侧的省略号图标,它将下拉,如果您单击底行的图标,它将向上下拉。

现在,我的实际实现(github page),代码完全相同(如下),但它想用 .dropup 替换所有 .dropdown 类打开时,包括被切断的最顶行,如下图所示。 enter image description here我已经为此苦苦挣扎了一个星期,但无法完全弄清楚。我已经尝试了一些不同的东西,我认为可以解决它,但最终只是一个 hack 并且不能在移动设备上工作,或者替换了一些但不是全部等。

这是我正在使用的 Javascript/jQuery,可以在 jsfiddle 和我的 github 源中看到 here .

$(document).on("shown.bs.dropdown", ".dropdown", function () {
// calculate the required sizes, spaces
var $ul = $(this).children(".dropdown-menu");
var $button = $(this).children(".song-menu");
var ulOffset = $ul.offset();
// how much space would be left on the top if the dropdown opened that direction
var spaceUp = (ulOffset.top - $button.height() - $ul.height()) - $('#playlist').scrollTop();
// how much space is left at the bottom
var spaceDown = $('#playlist').scrollTop() + $('#playlist').height() - ((ulOffset.top + 10) + $ul.height());
// switch to dropup only if there is no space at the bottom AND there is space at the top, or there isn't either but it would be still better fit
if (spaceDown < 0 && (spaceUp >= 0 || spaceUp > spaceDown))
$(this).addClass("dropup");
}).on("hidden.bs.dropdown", ".dropdown", function() {
// always reset after close
$(this).removeClass("dropup");
});

编辑:为了消除任何混淆,这里有一个没有我添加的 .dropup 函数的行为示例。 jsfiddle请注意,当您单击最后一个菜单项时,它会打开菜单但需要滚动。在这种情况下,我特别想删除 .dropdown 类并添加 .dropup,因此不需要滚动。

最佳答案

这需要一些基本的数学知识,但我设法弄清楚了你想做什么。此代码根据可用于普通下拉菜单的空间更改下拉菜单和下拉菜单之间的 Bootstrap 类。

我通过减去按钮的高度、下拉菜单以及按钮在 scrollContainer 中从 scrollContainer 的高度向下滚动的距离来计算这一点。通过使用按钮偏移量并减去 scrollContainer 的偏移量,我得到了 div 向下滚动了多少的值。

这是我的 jQuery(我选择了 .playlist 类,因为它附加到您的 scrollContainer,但您应该用 id 替换它或通过其他方式选择它):

$(".dropdown, .dropup").click(function(){
var dropdownClassCheck = $(this).hasClass('dropdown');
var buttonOffset = $(this).offset().top;
var scrollboxOffset = $('.playlist').offset().top;
var buttonHeight = $(this).height();
var scrollBoxHeight = $('.playlist').height();
var dropDownButtonHeight = $(this).children('ul').height();
dropdownSpaceCheck = scrollBoxHeight>buttonOffset-scrollboxOffset+buttonHeight+dropDownButtonHeight;
if(dropdownClassCheck && !dropdownSpaceCheck){
$(this).removeClass('dropdown').addClass('dropup');
}
else if(!dropdownClassCheck && dropdownSpaceCheck){
$(this).removeClass('dropup').addClass('dropdown');
}
});

工作JSFiddle

如果有部分代码可以改进/更容易完成,或者我的解决方案是否有任何问题,请告诉我。

关于javascript - 用 Dropup 替换 Bootstrap Dropdown(两个几乎相同的实现的不同事件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40122196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com