【问题标题】:Getting elements that exceed the maxium value. JAVASCRIPT/JQUERY获取超过最大值的元素。 JAVASCRIPT/JQUERY
【发布时间】:2010-12-07 06:22:16
【问题描述】:

你好,

我是 java 脚本的新手,所以请耐心等待! 我想使用JQuery 选择器来实现一些目标。

我有一个列表菜单。好像是这样的……

<ul style="width:auto">
<li>item one</li>
<li>item two</li>
<li>item three</li>
<li>item four</li>
<li>item five</li>
</ul>

好的,所以目前我正在使用parseInt 函数来检索ul 的当前宽度的整数值。

var ul = $("ul");
var currentWidth = parseInt(ul.width);
var maxWidth = 400;

有了当前宽度,我现在想创建一个 if 语句。 这对我来说真的很棘手。

if(currentWidth <= maxWidth){
alert('great job, do nothing');
}
else {
  // WHAT DO I DO?!
  // I need to take all the elements that makes the ul exceed that maxWidth variable and assign them to a new array called extraItems
}

那么我如何获得这些物品。我担心这远远超出了基础!

任何帮助将不胜感激!

客观示例图片:imageShack link

【问题讨论】:

  • 只是提示,使用 parseInt 时,您应该始终包含第二个参数,因此在您的情况下,请使用 parseInt(ul.width,10) 以确保它使用基数 10。

标签: jquery get find width elements


【解决方案1】:
else {
   var extraItems = [];
   $('ul li').each(function(i, e) {
      if ($(e).width() > maxWidth) {
         $(e).remove(); //? dunno if you want to remove em, but here's how
         extraItems.push(e);
      }
   });
   ...
}

【讨论】:

  • he 数组返回 null/empty 如果我正确阅读了您的位,您正在执行“如果列表项大于 ul 的最大宽度,则将其删除并将其放入数组中”此逻辑是正确的,但它与超过 maxWidth 的单个列表项有关。上面的示例引用了一个宽度为 400 且所有列表项组合为 500 的列表。取出每个超过最大值的列表项并将其放入数组中。所以,如果前 3 个项目加起来等于 440,再加上一个,得到 520,那么最后一个项目应该被发送到数组。
【解决方案2】:

我会这样处理:

// given these values:
var ul = $("ul");
var maxWidth = 200;

// the total width counter
var acc = 0;  

// find the li's and use the map (or filter) function to filter away unwanted elements
var overflow = ul.find('li').map(function(){

  // add current elm's width to our total
  acc += $(this).outerWidth();

  // within bounds - return nothing
  if ( acc < maxWidth ) {
    return null;
  }
  // limit reached - return element
  else {
    return this;
  }

});

// we are left with only the "overflow" elements...
overflow.hide();

【讨论】:

  • 正是我想要的。
【解决方案3】:

查看 Andreas Grech 的 community wiki 帖子...您也可以创建自己的选择器来执行此操作。

编辑:哦,在阅读了您的最终目标(隐藏溢出)之后,为什么不在您的内容包装器上使用 CSS 类 overflow:hidden,然后使用像 scrollTo 这样的插件来移动它?

Edit #2 LOL 抱歉编辑了这么多...如果你只是为了学习,试试这段代码(我也在 pastebin 中运行它),还要确保你查看 CSS, li 默认为 100% 宽度:

$(document).ready(function(){
 var ul = $("ul");
 var currentWidth = ul.width();
 var maxWidth = 400;
 if(currentWidth <= maxWidth){
  alert('great job, do nothing');
 } else {
  var liWidth = 0;
  var done = false;
  ul.find('li').each(function(indx){
   liWidth += $(this).width();
   if (liWidth > maxWidth && !done){
    ul.find('li:gt(' + (indx-1) + ')').hide();
    var done = true;
   }
  })
 }
 var savedLi = ul.find('li:hidden');
 alert( savedLi.length + ' elements were hidden');
})

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多