Javascript 如何获得li元素中的最大宽度

Javascript 如何获得li元素中的最大宽度,javascript,jquery,Javascript,Jquery,Ex(伪代码): 或 问题: 我想获得列1和列2的最大宽度,然后添加结果并设置为主包装的宽度: 总宽度=列1+列2 $('.main wrapper').css('width',totalWidth) 我的意思是: var $listing = $(this).find('ul.menu .extended ul li'); var $col1, $col2; // Loop through all target submenu lists $listing.each(function(key

Ex(伪代码):

问题: 我想获得
列1
列2
的最大宽度,然后添加结果并设置为
主包装的宽度
: 总宽度=列1+列2 $('.main wrapper').css('width',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);

但是我的脚本只有在文本没有空格的情况下才能正确获取宽度。

这是一段非常奇怪的代码,您应该研究更好的方法来实现这一点。同时,我将您的代码放在JSFIDLE中,$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);

我认为这样就可以了。

这是一段非常奇怪的代码,您应该研究更好的方法来实现这一点。同时,我将您的代码放在JSFIDLE中,$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);

我认为这样就可以了。

我建议您让CSS确定每个“列”的宽度,并将这些值相加

由于.column1和.column2是列表元素(
display:list item;
),因此它们的宽度始终与展开以适合最大子项的宽度相同

见:

将它们设置为
display:inline块其余的应该很简单

见:


我建议您让CSS确定每个“列”的宽度,并将这些值加在一起

由于.column1和.column2是列表元素(
display:list item;
),因此它们的宽度始终与展开以适合最大子项的宽度相同

见:

将它们设置为
display:inline块其余的应该很简单

见:


这是我对我的问题的解答。谢谢大家的支持

(function ($) {

  Drupal.behaviors.menu = {
    attach: function (context, settings) {


      /** SOF Block: Populate the menu items to each columns **/
      var $lists = $('#navigation li.expanded ul.menu'); 

      // Loop through all target lists.
      $lists.each(function(i, e) {

        var $list = $(e);
        // Count all the items
        var $count_list = $(this).find('li').size();
        // Get the ceiling for first column
        var $sliced_list = Math.ceil($count_list / 2);

        if($count_list > 5) {

          //These are temporary variables.
          var $new_list = $('<ul>');
          var $list_item, $sub_list, $sub_set;

          // Set the number of items per column when less than 9
          if($count_list < 9) {
            // The number of items per column.
            var per_column = 5;
          } 

          // Dynamic number of items per column when more that or equal to 9
          if($count_list >= 9) {
            var per_column = $sliced_list;
          }

          // Calculate the amount of columns needed.
          var n = Math.ceil($list.find('li').length / per_column);

          // Loop through all columns.
          for (var i = 0; i < n; ++i) {

            // Creates the sub list for the current column.
            $sub_list = $('<ul class="columns column' + (i + 1) + '">');
            // Gets the first set of list items from the original list and adds them to the sub list created above.
            $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);
            // Creates a new list item and adds the sub list to it.
            $list_item = $('<li class="extended extended' + (i + 1) + '">').append($sub_list);
            // Add the newly created list item to the new list.
            $new_list.append($list_item);
            // Create a div with the class 'columnX' and wrap the sub list with it.
            //$sub_list.wrap('<div class="columns column' + (i + 1) + '"></div>');

          }

          // Replace the original list with the new one.
          $list.html($new_list.html());

        }
      }); 
      /** EOF Block: Populate the menu items to each columns **/

      /** SOF Block: Apply all necessary changes to focused menu items **/
      // Set all settings required on hover
      $('#navigation ul li.expanded').hover(function() {
        $(this).children().next('ul').css('display', 'block');
        $(this).addClass('hover'); 
        // Get the width of parent li
        var w = $(this).width();
        // Apply the width to the "div class='fix'" element to avoid overlapping
        $(this).children().next('div').css('width', w + 'px');      
      }, function() {
        $(this).children().next('ul').css('display', 'none');
        $(this).removeClass('hover');
      });
      /** EOF Block: Remove all changes applied to all focused menu items on mouseouot **/    

    }
  };
})(jQuery);
(函数($){
Drupal.behaviors.menu={
附加:功能(上下文、设置){
/**SOF块:填充每个列的菜单项**/
var$lists=$(“#导航li.expanded ul.menu”);
//循环浏览所有目标列表。
$lists.每个功能(即,e){
变量$list=$(e);
//清点所有物品
var$count_list=$(this.find('li').size();
//得到第一根柱子的天花板
var$sliced\u list=Math.ceil($count\u list/2);
如果($count_list>5){
//这些是临时变量。
var$new_list=$(“
    ”); 变量$list\u item、$sub\u list、$sub\u set; //设置少于9时每列的项目数 如果($count\u list<9){ //每列的项目数。 每列var=5; } //当大于或等于9时,每列的动态项目数 如果($count\u list>=9){ 每列变量=$sliced\u列表; } //计算所需的列数。 var n=Math.ceil($list.find('li')。长度/每列); //循环遍历所有列。 对于(变量i=0;i); //从原始列表中获取第一组列表项,并将它们添加到上面创建的子列表中。 $sub_set=$list.find('li').slice(0,每列)。appendTo($sub_list); //创建新列表项并将子列表添加到其中。 $list_item=$('
  • )。追加($sub_list); //将新创建的列表项添加到新列表中。 $new\u list.append($list\u项); //使用“columnX”类创建一个div,并用它包装子列表。 //$sub_list.wrap(“”); } //将原始列表替换为新列表。 $list.html($new_list.html()); } }); /**EOF块:填充每个列的菜单项**/ /**SOF块:对聚焦菜单项应用所有必要的更改**/ //设置悬停时所需的所有设置 $('#navigation ul li.expanded')。悬停(函数(){ $(this).children().next('ul').css('display','block'); $(this.addClass('hover'); //获取父li的宽度 var w=$(this.width(); //将宽度应用于“div class='fix'”元素以避免重叠 $(this.children().next('div').css('width',w+'px'); },函数(){ $(this).children().next('ul').css('display','none'); $(this.removeClass('hover'); }); /**EOF块:删除应用于鼠标上所有聚焦菜单项的所有更改**/ } }; })(jQuery);
这是我的问题解决方案。谢谢大家的支持

(function ($) {

  Drupal.behaviors.menu = {
    attach: function (context, settings) {


      /** SOF Block: Populate the menu items to each columns **/
      var $lists = $('#navigation li.expanded ul.menu'); 

      // Loop through all target lists.
      $lists.each(function(i, e) {

        var $list = $(e);
        // Count all the items
        var $count_list = $(this).find('li').size();
        // Get the ceiling for first column
        var $sliced_list = Math.ceil($count_list / 2);

        if($count_list > 5) {

          //These are temporary variables.
          var $new_list = $('<ul>');
          var $list_item, $sub_list, $sub_set;

          // Set the number of items per column when less than 9
          if($count_list < 9) {
            // The number of items per column.
            var per_column = 5;
          } 

          // Dynamic number of items per column when more that or equal to 9
          if($count_list >= 9) {
            var per_column = $sliced_list;
          }

          // Calculate the amount of columns needed.
          var n = Math.ceil($list.find('li').length / per_column);

          // Loop through all columns.
          for (var i = 0; i < n; ++i) {

            // Creates the sub list for the current column.
            $sub_list = $('<ul class="columns column' + (i + 1) + '">');
            // Gets the first set of list items from the original list and adds them to the sub list created above.
            $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);
            // Creates a new list item and adds the sub list to it.
            $list_item = $('<li class="extended extended' + (i + 1) + '">').append($sub_list);
            // Add the newly created list item to the new list.
            $new_list.append($list_item);
            // Create a div with the class 'columnX' and wrap the sub list with it.
            //$sub_list.wrap('<div class="columns column' + (i + 1) + '"></div>');

          }

          // Replace the original list with the new one.
          $list.html($new_list.html());

        }
      }); 
      /** EOF Block: Populate the menu items to each columns **/

      /** SOF Block: Apply all necessary changes to focused menu items **/
      // Set all settings required on hover
      $('#navigation ul li.expanded').hover(function() {
        $(this).children().next('ul').css('display', 'block');
        $(this).addClass('hover'); 
        // Get the width of parent li
        var w = $(this).width();
        // Apply the width to the "div class='fix'" element to avoid overlapping
        $(this).children().next('div').css('width', w + 'px');      
      }, function() {
        $(this).children().next('ul').css('display', 'none');
        $(this).removeClass('hover');
      });
      /** EOF Block: Remove all changes applied to all focused menu items on mouseouot **/    

    }
  };
})(jQuery);
(函数($){
Drupal.behaviors.menu={
附加:功能(上下文、设置){
/**SOF块:填充每个列的菜单项**/
var$lists=$(“#导航li.expanded ul.menu”);
//循环浏览所有目标列表。
$lists.每个功能(即,e){
变量$list=$(e);
//清点所有物品
var$count_list=$(this.find('li').size();
//得到第一根柱子的天花板
var$sliced\u list=Math.ceil($count\u list/2);
如果($count_list>5){
//这些是临时变量。
var$new_list=$(“
    ”); 变量$list\u item、$sub\u list、$sub\u set; //设置少于9时每列的项目数 如果($count\u list<9){ //我的电话号码是多少
    /* css */
    li.expanded { display: inline-block; }​
    
    /* js */
    var totalWidth = $('.column1').width() + $('.column2').width();
    $('.main-wrapper').width(totalWidth);​
    
    (function ($) {
    
      Drupal.behaviors.menu = {
        attach: function (context, settings) {
    
    
          /** SOF Block: Populate the menu items to each columns **/
          var $lists = $('#navigation li.expanded ul.menu'); 
    
          // Loop through all target lists.
          $lists.each(function(i, e) {
    
            var $list = $(e);
            // Count all the items
            var $count_list = $(this).find('li').size();
            // Get the ceiling for first column
            var $sliced_list = Math.ceil($count_list / 2);
    
            if($count_list > 5) {
    
              //These are temporary variables.
              var $new_list = $('<ul>');
              var $list_item, $sub_list, $sub_set;
    
              // Set the number of items per column when less than 9
              if($count_list < 9) {
                // The number of items per column.
                var per_column = 5;
              } 
    
              // Dynamic number of items per column when more that or equal to 9
              if($count_list >= 9) {
                var per_column = $sliced_list;
              }
    
              // Calculate the amount of columns needed.
              var n = Math.ceil($list.find('li').length / per_column);
    
              // Loop through all columns.
              for (var i = 0; i < n; ++i) {
    
                // Creates the sub list for the current column.
                $sub_list = $('<ul class="columns column' + (i + 1) + '">');
                // Gets the first set of list items from the original list and adds them to the sub list created above.
                $sub_set = $list.find('li').slice(0, per_column).appendTo($sub_list);
                // Creates a new list item and adds the sub list to it.
                $list_item = $('<li class="extended extended' + (i + 1) + '">').append($sub_list);
                // Add the newly created list item to the new list.
                $new_list.append($list_item);
                // Create a div with the class 'columnX' and wrap the sub list with it.
                //$sub_list.wrap('<div class="columns column' + (i + 1) + '"></div>');
    
              }
    
              // Replace the original list with the new one.
              $list.html($new_list.html());
    
            }
          }); 
          /** EOF Block: Populate the menu items to each columns **/
    
          /** SOF Block: Apply all necessary changes to focused menu items **/
          // Set all settings required on hover
          $('#navigation ul li.expanded').hover(function() {
            $(this).children().next('ul').css('display', 'block');
            $(this).addClass('hover'); 
            // Get the width of parent li
            var w = $(this).width();
            // Apply the width to the "div class='fix'" element to avoid overlapping
            $(this).children().next('div').css('width', w + 'px');      
          }, function() {
            $(this).children().next('ul').css('display', 'none');
            $(this).removeClass('hover');
          });
          /** EOF Block: Remove all changes applied to all focused menu items on mouseouot **/    
    
        }
      };
    })(jQuery);