Javascript 如何使用jquery获取li宽度+边距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2407229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get li width + margin using jquery
提问by trrrrrrm
my code is something like this
我的代码是这样的
//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>
how to make a jquery function that will take an li index as an input and it will return the width of all li from the beginning to that index + margins ' left + right '
如何制作一个将 li 索引作为输入的 jquery 函数,它将返回从开始到该索引的所有 li 的宽度 + 边距“左+右”
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] ))
回答by Alex Sexton
You're looking for outerWidth(true)
您正在寻找 outerWidth(true)
for example
例如
$('li:eq(0)').outerWidth(true)
$('li:eq(0)').outerWidth(true)
if you dont want the margin, but only want the padding and border, just do outerWidth()
如果你不想要边距,而只想要填充和边框,那就做 outerWidth()
So you can just add up the li's outerWidth's normally to get the sum of them all.
所以你可以正常地将 li 的外层宽度相加得到它们的总和。
回答by gnarf
$.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);
回答by jitter
//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)
}

