li高度的动态计算

dynamic calculation of li height

本文关键字:计算 动态 高度 li      更新时间:2023-09-26

我有以下代码

问题是,目前我是硬编码的高度时,悬停为300,我如何做到这一点,使它得到的高度基于

  • 标签的数量,所以说有6
  • 和每个li是50px的高度,那么高度是300。

    我指的是这一行:

     $(this).stop().animate({"height":"300px"},1000).addClass("dropped");
    

    如何使它在已经展开的情况下,我再次点击它它会回到未展开的

  • 获取ul的高度,然后设置#可扩展动画高度。

    $("#expandable").click(function() {
        var ulHeight = $(this).children("ul").height() + 50;
        $(this).stop().animate({"height":ulHeight + "px"},1000).addClass("dropped");
    });
    

    试试这个代码

    $("#expandable").hover(function() {
         var _aH = (parseInt($(this).find('ul li').length)+1)*50
        $(this).stop().animate({"height":_aH+"px"},1000).addClass("dropped");
    }, function() {
        $(this).stop().animate({"height":"50px"},1000).removeClass("dropped");
    });
    

    看到小提琴

    基本上,你需要计算ulli的数量,然后找出total height
    代码假设50px是li的高度,您可以通过抓取li的高度使其也通用。

    首先,您需要使用</ul>而不是</nav>关闭ul

    其次,要使其动态而不是硬编码高度,您需要计算列表的总高度。你可以这样做:

    var sum = 50;
    $('#expandable').find('li').each(function() {
       sum += $(this).height();
    });
    $("#expandable").click(function() {
        $(this).stop().animate({"height": sum},1000).addClass("dropped");
    });
    

    工作演示

    您可以像这样使用jQuery获取ul的高度:

    $('#expandable').find('ul').height();
    …然后添加span的高度就得到了动画的计算高度:)

    至于你的其他问题:只要检查你的dropped类和动画它回来,如果它在那里:

    $("#expandable").click(function() {
       var ulHeight = $('#expandable').find('ul').height();
       var spanHeight = $('span').height();
       var computedHeight = (ulHeight + spanHeight);
        if( $(this).hasClass('dropped') ) {
            $(this).stop().animate({"height": (spanHeight + "px") },1000).removeClass("dropped");
            return false;
        }
       $(this).stop().animate({"height": (computedHeight + "px") },1000).addClass("dropped");
    });
    

    看我的小提琴:小提琴