我编写了一个从jQuery $(document).ready()调用的javascript函数。这将解析父div的所有子级,并且仅更新最右边的子级。
html
...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....
javascript
$(document).ready(function(){
stretchDivs();
});
function stretchDivs() {
// loop thru each <div> that has class='stretch'
$("div.stretch").each(function(){
// get the inner width of this <div> that has class='stretch'
var totalW = parseInt($(this).css("width"));
// loop thru each child node
$(this).children().each(function(){
// subtract the margins, borders and padding
totalW -= (parseInt($(this).css("margin-left"))
+ parseInt($(this).css("border-left-width"))
+ parseInt($(this).css("padding-left"))
+ parseInt($(this).css("margin-right"))
+ parseInt($(this).css("border-right-width"))
+ parseInt($(this).css("padding-right")));
// if this is the last child, we can set its width
if ($(this).is(":last-child")) {
$(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
} else {
// this is not the last child, so subtract its width too
totalW -= parseInt($(this).css("width"));
}
});
});
}