获取内部元素的宽度并使用它来设置外部元素的宽度
Get a width of inner elemets and use it to set a width of outer element
我有这个代码。但这行不通。我需要设置所有的总宽度,然后用它来换行div。http://jsfiddle.net/8jPcP/
<div id="breadcrumb-wrapper">
<div>
<a href="">asd</a>
<a href="">asd</a>
<a href="">asd</a>
<a href="">asd</a>
<a href="">asd</a>
</div>
</div>
将代码改为
var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function(index, el) {
totalWidth = totalWidth + $(this).width();
});
$('#breadcrumb-wrapper > div').width(totalWidth);
像这样更新你的脚本
var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function() {
totalWidth = totalWidth + $(this).width();
/* alert(totalWidth);*/
});
$('#breadcrumb-wrapper > div').width(totalWidth);
查看已更新的jsfiddle
http://jsfiddle.net/8jPcP/1/工作函数是这样的:
var totalWidth = 0;
$('#breadcrumb-wrapper a').each(function(index, el) {
var newWidth = totalWidth + $(this).width();
totalWidth = newWidth;
});
$('#breadcrumb-wrapper > div').width(totalWidth);
你在循环中使用var newWidth设置newWidth,因此在循环范围内声明了一个不同的变量
相关文章:
- 使用 JavaScript 一次为一个元素设置多个属性
- 为dropdownlistfor(MVC)中的每个元素设置唯一id
- 无法为HTML5中具有画布和图像的可拖动元素设置“拖动图像”
- Jquery为每个元素设置属性
- 在JSON数组中进行迭代,并为其元素设置样式
- 将jquery ui窗口的父元素设置为另一个元素
- 如何使用随机css id为元素设置样式
- 如何为所有子元素设置填充
- Javascript:为元素设置适当的事件处理程序
- 为已设置动画的元素设置动画
- 将HTML元素设置为可滚动
- jQuery:从 JSON 对象为元素设置值
- 如何为 HTML 中的多个元素设置相同的 ID
- 为动态创建的元素设置属性
- 同时为一个 Li 元素设置类“活动”
- 如何使用 javascript 为元素设置内联 css 样式
- 如何为动态添加的 html 元素设置 setCustomValidity()
- 为包含 HTML 标记的字符串中的元素设置 Style 属性
- 获取两个元素的高度,将另一个元素设置为该高度
- 为表单元素设置 Cookie