2009-10-16 28 views
0

問候,獲取超過最大值的元素。 JAVASCRIPT/JQUERY

我是新的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

+1

只是一個提示,使用parseInt函數的時候,你應該總是包含第二個參數,所以你的情況,使用parseInt(ul.width,10)來確保它使用基數10. – Deeksy 2009-10-16 05:19:20

回答

1

這是我會怎麼對付它:

// 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(); 
+0

正是我在找什麼。 – Erik5388 2009-10-17 23:15:33

4
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); 
     } 
    }); 
    ... 
} 
+0

他數組返回s空/空 如果我正在讀你的位,你正在做「如果列表項大於ul的最大寬度,那麼將其移除並放入數組中」 這個邏輯是正確的,但它與一個超過maxWidth的單個列表項。 上面的例子指的是一個寬度爲400的列表,並且所有列表項目的組合都是500.取每個列表項目超過最大值並將其放入數組中。所以,如果3個第一項全部在一起等於440並且給我們增加一個520,那麼最後的項應該被髮送到陣列。 – Erik5388 2009-10-16 12:59:55

1

看看這個community wiki後由Andreas格列奇......你可以讓你自己選擇要做到這一點爲好。

編輯:呵呵,看完你的最終目標是什麼(隱藏溢出),爲什麼不在你的內容包裝上使用CSS類overflow:hidden,然後用scrollTo這樣的插件來移動它?

編輯#2大聲笑對不起編輯這麼多...如果你只是做這個學習,試試這個代碼(我也有它運行在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'); 
}) 
+0

該死!我需要學習更快地輸入。 :-) – Borgar 2009-10-16 16:01:51