How to add elements into one div until it's width almost equal to another div?
I have 2 containers, one inside the other, and I'm trying to fill the inner container with elements on document.ready so it's width is almost equal to the outer's div width.
It works perfectly with "if" statement on window.resize, but since I need to fill the div on document.ready I'm trying to use "while" and it doesn't work. Why?
Here is the HTML:
<style>
#outer {float: left; width: 500px; background: grey}
#inner {float: left; width: auto;}
li {float: left; margin: 0 10px}
</style>
<div id="outer">
<ul id="inner">
<li></li>
开发者_运维百科 <li></li>
<li></li>
</ul>
</div>
...and JS:
function width_check() {
var ddd = $("#outer").width() - $("#inner").width();
var sss = 0;
if (ddd > 100) {
sss = 1;
} else { sss = 0 };}
$(document).ready function() {
width_check();
while (sss = 1) {
$("#inner").append('<li></li>');
width_check();
} }
I think you have a scope problem here.
You have a function that defines var sss = 0
. But the check of $(document).ready
has its own sss. sss is undefined in this function. Try something like:
function width_check()
{
var ddd = $("#outer").width() - $("#inner").width();
return ddd > 100;
}
$(document).ready( function() // check the extra brackets around the function.
{
while(width_check()) // check the width every time
{
$("#inner").append('<li></li>');
}
});
Do like marnix says, and add display: block;
to your li
s
精彩评论