English 中文(简体)
如何使用jQuery获取li宽度+边距
原标题:how to get li width + margin using 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>

如何制作一个jQuery函数,它将以li索引作为输入,并返回从开始到该索引的所有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] )) 
最佳回答

你正在寻找outerWidth(true)

例如

$( li:eq(0) ).outerWidth(true) 的中文翻译为:$( li:eq(0) ).outerWidth(true)

如果您不需要边距,只需要填充和边框,请使用outerWidth()

所以您可以正常将Li的outerWidth相加以得到它们的总和。

问题回答
$.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);
//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)
}




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签