【问题标题】:Counting <ul> height with Javascript用 Javascript 计算 <ul> 高度
【发布时间】:2012-07-20 20:57:28
【问题描述】:

这是我的情况。我有一个像这样的滑动 jquery 菜单:http://tympanus.net/codrops/2011/07/03/sliding-background-image-menu.

菜单代码为:

<div id="sbi_container" class="sbi_container">
        <div class="sbi_panel" data-bg="images/1.jpg">
            <a href="#" class="sbi_label">About</a>
            <div class="sbi_content">
                <ul>
                    <li><a href="#">Subitem</a></li>
                    <li><a href="#">Subitem</a></li>
                    <li><a href="#">Subitem</a></li>
                </ul>
            </div>
        </div>
        <div class="sbi_panel" data-bg="images/2.jpg">
            ...
        </div>

CSS:

.sbi_content{
    position:absolute;
    border-top:2px solid #000;
    bottom:90px;
    left:0px;
    width:100%;
    background:transparent url(../images/pattern.png) repeat top left;
    display:none;
    overflow:hidden;
}
.sbi_content ul{
    padding:10px;
}
.sbi_content ul a{
    display:block;
    color:#f0f0f0;
    font-size:16px;
    padding:4px 6px 4px 14px;
    background:transparent url(../images/triangle.png) no-repeat 3px 50%;
    opacity:0.9;
}
.sbi_content ul a:hover{
    background-color:#000;
    color:#fff;
    -moz-box-shadow:1px 1px 5px #000;
    -webkit-box-shadow:1px 1px 5px #000;
    box-shadow:1px 1px 5px #000;
}

这是一个我遇到问题的 JavaScript 片段:

    $content.each(function(i) {
            var $el = $(this);
// save each content's height (where the menu items are)
// and hide them by setting the height to 0px
            var num = $el.find('ul li').size();

            $el.data( 'height', num * 35 + 10 ).css( 'height', '0px' ).show();
                    });

我需要计算这些&lt;ul&gt; 的高度。 我现在正在做的是计算有多少 &lt;li&gt; 项目,然后将其乘以一个人的高度数(35)并添加 10px 作为边距..

一切都会好的,但是当有一个很长的&lt;li&gt; 项目时,它会跳转到第二行,问题是这段代码不计算第二行的高度。

有什么办法可以解决这个问题吗?

谢谢。

【问题讨论】:

  • 你试过了吗:$('#your-ul').outerHeight()
  • 是的,我已经尝试过了,然后继续进行。可以看这里:vladsworkshop.lt/newsite
  • item中有多个单词时,id在submenu下面加了一个空格..我真的不知道为什么..

标签: javascript jquery jquery-plugins height


【解决方案1】:

您可以使用scrollHeight 属性:

$("ul")[0].scrollHeight

针对您的具体情况 -

$content.find('ul')[0].scrollHeight

【讨论】:

  • 写入时:var num = $el.find('ul')[0].scrollHeight; num=0 对我来说很重要。为什么?
  • 这有点奇怪,因为我能找到的所有内容都是:var $el = $(this);(您可以在我的主要帖子中的第一行 Java 脚本中看到它)。还是这不是?
  • var $content = $el.find('div.sbi_content')
  • 你不需要 $content.each()... 你可以直接做 $content.find('ul')[0].scrollHeight... 实际上只做 $('div .sbi_content ul')[0].scrollHeight 获取ul的高度
  • 嗯.. 我开始明白了。但是我应该如何写这一切,以防我最终需要得到$el.data( 'height', "number" ).css( 'height', '0px' ).show(); });
【解决方案2】:

您可以使用以下方法计算内容中所有lis 的高度:

var totalLiHeight = 0;
$el.find('ul li').each(function() {
    var currentLiHeight = $(this).height();
    totalLiHeight += currentLiHeight;
});

然后你可以添加边距。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签