有些时候,在一个网页的ul li中,存在左右两个部分的内容,但是右边元素内容又是不固定,左边元素相对应的不能用固定宽度,所有需要我们动态的获取右边元素宽度,来赋值给左边元素的marginRight值。
HTML结构:
-
头像
名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字
工具1
工具2
工具3
-
头像
名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字
工具2
工具3
-
头像
名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字名字
工具3
配上CSS:
html,body{padding:0;margin:0}
ul,li{list-style:none;padding:0;margin:0}
p{margin:0;padding:0}
.itemCon{width:450px;height:auto; margin:100px auto; background:#ccc; overflow:hidden}
.item{width:100%; float:left;height:60px;border-bottom:solid 1px #f00; position:relative}
.leftMess{ height:60px;}
.leftCon{ float:left; height:60px; overflow:hidden;width:100%}
.leftMess span{ display:inline-block;width:50px;height:50px; border-radius:50%; background:#f00; text-align:center; line-height:50px; margin:5px; float:left}
.leftMess p{ margin-left:60px}
.rightMess{width:auto;height:60px; position:absolute;right:0;top:0}
.rightMess span{width:50px; height:50px; line-height:50px; text-align:center; margin:5px; float:left; background:#f00}
最后JS代码:
var divs = document.getElementsByClassName('item');
for (var i = 0; i < divs.length; i++) {
var lastW = divs[i].children[1].offsetWidth;
divs[i].children[0].style.marginRight=lastW+"px"
}
最终效果图:
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!