2010-03-09 13 views
7

mein Code ist so etwas wie dieswie li Breite + Marge mit Jquery

//css 
li{display:inline-block} 

//html #li margin and width are dynamic 
<ul> 
<li style='margin:30px;width:100px;'>Pic</li> 
<li style='margin:40px;width:200px;'>Pic</li> 
<li style='margin:10px;width:500px;'>Pic</li> 
<li style='margin:50px;width:300px;'>Pic</li> 
</ul> 

zu bekommen, wie eine jQuery-Funktion zu machen, die einen li Index als Eingabe verwenden und es wird die Breite aller li Rückkehr aus der Anfang zu diesem Index + Margen 'links + rechts'

Examples // something like this 
myFunction(1); //output 440 ((30 margin-left [0] + 30 margin-right [0] + 40 margin-left [1] + 40 margin-right [1] + 100 width [0] + 200 width [1])) 

myFunction(2); //output 960 ((30 margin-left [0] + 30 margin-right [0] + 40 margin-left [1] + 40 margin-right [1] + 10 margin-left [2] + 10 margin-right [2] + 100 width [0] + 200 width [1] + 500 width [2])) 

Antwort

26

Sie suchen outerWidth(true)

zum Beispiel

$('li:eq(0)').outerWidth(true)

wenn Sie den Rand nicht wollen, wollen aber nur die Polsterung und Grenze, tun nur outerWidth()

So können Sie nur die outer des Li summieren sich normalerweise die Summe von allen zu bekommen.

+0

dieser Ausgang der outWidth für 1 Element, aber ich möchte, dass meine Funktion die Summe aus dem ersten Element zu diesem Element zu Ausgang, hast du was ich meine? Vielen Dank für Ihre Hilfe – trrrrrrm

+2

@ From.ME.to.YOU: Alex Sexton hat Ihnen die Tür gezeigt, aber Sie müssen es selbst öffnen. – anddoutoi

+0

die Tür wurde geöffnet: D danke Alex – trrrrrrm

0
//adapt selectors to get only the ul you want 
function calculate(i) { 
    if(i >= $("ul").size()) { 
    alert("This index doesn't exist"); 
    return; 
    } 
    var sum = 0; 
    for(var j=0; j<=i; j++) { 
    sum = sum + $("ul li:eq("+j+")").outerWidth(true); 
    } 
    alert("li's width for index "+i+" is "+sum) 
} 
2
$.fn.sumOuterWidth = function(useMargins) { 
    var sum = 0; 
    this.each(function() { 
    sum += $(this).outerWidth(useMargins); 
    }); 
    return sum; 
}; 

// example sum the width of the first 2 li's: 
$('ul li').slice(0,2).sumOuterWidth(true) 

// Also gets the sum of the width of the first 2 li's: 
$('ul li:eq(1)').prevAll().andSelf().sumOuterWidth(true);