<head>
<title>平分秋色</title>
<style type="text/css">
.div1
{
width:90px
float:left
}
.div2
{
width:80px
float:left
}
div
{
border:1px solid #EEEEEE
}
</style>
<script type="text/javascript">
window.onload = function () {
rePointAll()
}
function rePointAll() {
rePoint("objElement", 0)
rePoint("objElement2", 0)
rePoint("objElement3", 90)//指定每个DIV的宽度
rePoint("td1", 0)
rePoint("td2", 80)//CSS样式指定的属性.style.width无法获取,所以要指定宽度
}
//指定间距,id:容器标签ID,w为间距、为0时取第一个元素的宽度值
function rePoint(id, w) {
var objElement = document.getElementById(id)//获取容器
var divs = objElement.getElementsByTagName("div")//获取其下元素
if (divs.length == 0) {//没有元素则结束
return
}
var width = w
if (width == 0) {//如果不指定元素宽度,去第一个元素宽度
//获取宽度,并正则去掉"px",不区分大小写,兼容措施
width = divs[0].style.width.replace(/px/i, "")
}
//间距 = (容器宽度 - 元素宽度 * 元素数量) / (元素数量 - 1)
var marginLeftIndex = parseInt((objElement.offsetWidth - (parseInt(width) * divs.length)) / (divs.length - 1))
if (marginLeftIndex <0) { //间距小于0时,则为0,
marginLeftIndex = 0
}
//循环为元素设定marginLeft(左间隔),n = 1,不为0是略过第一个元素
for (var n = 1n <divs.lengthn++) {
divs[n].style.marginLeft = marginLeftIndex + "px"//+px 为兼容
}
}
</script>
</head>
<body>
<div id="objElement" style="width:100%">
<div style="width:100pxfloat:left">1</div><div style="width:100pxfloat:left">1</div><div style="width:100pxfloat:left">1</div><div style="width:100pxfloat:left">1</div><div style="width:100pxfloat:left">1</div>
</div>
<br/>
<div id="objElement2" style="width:100%">
<div style="width:120pxfloat:left">2</div><div style="width:120pxfloat:left">2</div><div style="width:120pxfloat:left">2</div><div style="width:120pxfloat:left">2</div>
</div>
<br/>
<div id="objElement3" style="width:100%">
<div class="div1">3</div><div class="div1">3</div><div class="div1">3</div><div class="div1">3</div><div class="div1">3</div><div class="div1">3</div>
</div>
<br/>
<table width="100%">
<tr><td id="td1"><div style="width:110pxfloat:left">4</div><div style="width:110pxfloat:left">4</div><div style="width:110pxfloat:left">4</div><div style="width:110pxfloat:left">4</div></td></tr>
<tr><td id="td2"><div class="div2">5</div><div class="div2">5</div><div class="div2">5</div><div class="div2">5</div><div class="div2">5</div><div class="div2">5</div></td></tr>
</table>
</body>
</html>
不是很明白你的意思,是不是比如把界面分为4列的意思?如果是,设置float:leftwidth:25%这样就可以了~注意设置宽度为百分比~
如果不是,请重新描述清楚~
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)