JQuery mCustomScrollbar动态高度

JQuery mCustomScrollbar dynamic height

本文关键字:高度 动态 mCustomScrollbar JQuery      更新时间:2023-09-26

我有一个带有下拉列表的表单。这个列表是动态生成的,我使用mCustomScrollbar来显示下拉列表中的元素。

mCustomScrollbar需要以px为单位固定高度。

<ul class=" customScroll" role="menu" aria-labelledby="dropdownMenu1" >
                                <li  >1</li>
                                <li >1</li>
                            </ul>

脚本:我在初始化脚本中尝试了各种参数即:自动展开滚动条

 $(".customScroll").mCustomScrollbar();

如果存在许多li元素,则这些参数可以正常工作,但在2-3个li元素的情况下,由于ul的高度超过了存在的元素,因此下拉列表中存在空白。

任何关于动态更改元素高度的想法。

谢谢,

您可以使用计算customScroll的高度

$(function() {
   function getChildrenHeight(element) {
      var height = 0;
      element.children().each(function() {height+= $(this).height();});
      return height;
  }
   $(".customScroll").height(getChildrenHeight($(".customScroll")));
});

您可以将函数getChildrenheight()与任何元素一起使用,以根据其所有子元素高度的总和来获得元素的高度。

我用这种方式解决了这个问题。

首先我增加了两个类。

.customScroll-auto{ height:auto ; overflow:hidden;}
.customScroll-fixed{ height:150px; overflow:hidden;}

然后在我的jquery文件中,我检查了

if(array_length > myLimit)
     add class customScroll-fixed to the ul element
else
     add class customScroll-auto to the ul element

我不知道这是否是正确的做法。但它对我有效。