例如(伪代码):
<ul class="menu">
<li class="extended">
<div class="columns column1">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
</div>
</li>
<li class="extended">
<div class="columns column2">
<ul>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
</ul>
</div>
</li>
</ul>
<ul class="menu">
<li class="extended">
<div class="columns column1">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</div>
</li>
<li class="extended">
<div class="columns column2">
<ul>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
</ul>
</div>
</li>
</ul>
目标是这样的:
Item 1 | Item 6
Item 2 | Item 7
Item 3 | Item 8
Item 4 | Item 9
Item 5 | Item 10
或
Item 1 | Item 7
Item 2 | Item 8
Item 3 | Item 9
Item 4 | Item 10
Item 5 | Item 11
Item 6
问题:
我想获取 column1
和 column2
的最大宽度,然后添加结果并设置为 main-wrapper
的宽度:
总宽度 = 第 1 列 + 第 2 列
$('.main-wrapper').css('宽度',totalWidth);
我的实现:
var $listing = $(this).find('ul.menu .extended ul li');
var $col1, $col2;
// Loop through all target submenu lists
$listing.each(function(key, value) {
var $t = $(value);
if(key == 0) {
// Get the width of the first column
$col1 = $t.outerWidth(true);
} else if(key == $listing.length-1) {
// Get the width of the second column
$col2 = $t.outerWidth(true);
}
});
// Store the total width of columns in variable
var $total_width = $col1 + $col2 + 46;
// Append the width in the parent ul element
$(this).find('ul.menu').css('width', $total_width);
但是如果文本没有空格,我的脚本只能正确获取宽度。
最佳答案
这是非常奇怪的代码,您应该研究更好的方法来做到这一点。同时,我将您的代码放入 JSFiddle 中,您的 $total_width 将返回为 NaN - 您应该设置初始的 $col1 和 $col2 = 0 - 这至少可以确保您获得一个可以使用的数值。
编辑:Alexander 是正确的 - $().find() 确实返回一个 jQuery 对象。在我的测试中,我删除了它并执行了 $.find() 并且没有 .each() 函数。
var $listing = $(this).find('ul.menu .extended ul li');
console.log($listing);
var $col1 = 0, $col2 = 0;
// Loop through all target submenu lists
$listing.each(function(key, value) {
var $t = $(value);
if(key == 0) {
// Get the width of the first column
$col1 = $t.outerWidth(true);
} else if(key == $listing.length-1) {
// Get the width of the second column
$col2 = $t.outerWidth(true);
}
});
// Store the total width of columns in variable
var $total_width = $col1 + $col2 + 46;
// Append the width in the parent ul element
$(this).find('ul.menu').css('width', $total_width);
我认为这会成功。
关于javascript - 如何获取 li 元素的最大宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12523863/