简体   繁体   中英

how to append divs to a specific div in jquery?

I am trying to dynamically fadeIn divs with a specific height and width and the same Id to a specific div with class myBox and randomly position them in myBox using the append() function. However divs are being appended inside and outside myBox .

This is my code. What is wrong?

var xx = Math.random() * 100;
for (var i = 0; i < xx; i++) {
  var $newdiv1 = $("<div id='object1' style='width: 100px; height: 100px; background: red ;'></div>");
  var top = Math.random() * 700 - 30;
  var left = Math.random() * 1200;

  $($newdiv1).css({
    "top": top,
    "left": left
  });

  $($newdiv1).css('background-color', getRandomColor);
  $(".myBox").append($newdiv1).fadeIn("slow");
}

By reviewing your question I think Rory's comment gives you the answer, but I just enhaced it. Need to set overflow: hidden property of css on main div to stop showing the child objects outside of main div.

Please review the snippet, or Fiddle here . Just added background color and opacity for better presentation.

 $(function(){ var xx = Math.random() * 100; for (var i = 0; i < xx; i++) { var $newdiv1 = $("<div id='object1' style='width: 100px; height: 100px; background: red ;'></div>"); var top = Math.random() * 700 - 30; var left = Math.random() * 1200; $($newdiv1).css({ "top": top, "left": left }); $($newdiv1).css('background-color', '#C00'); //getRandomColor); $(".myBox").append($newdiv1).fadeIn("slow"); } }); 
 .myBox { width: 500px; height: 300px; position: relative; background-color: orange; overflow: hidden; } .myBox div { position: absolute; opacity: 0.5; border: 1px solid green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myBox"></div> 

Hope this will help you.

Appending seems to be done correctly, but the first problem I can see here is that you are setting top and left attributes, but position attribute is not set. You should add to your stylesheet something that will specify position attribute for the main container and child divs. Example:

.myBox {
  position: absolute;
}

.myBox div {
  position: relative;
}

Also another thing. You specify $newdiv1 as jQuery object:

var $newdiv1 = $(...)

And then you again wrap it with $(). This should be enough:

$newdiv1.css({
    "top": top,
    "left": left
  });
$newdiv1.css('background-color', getRandomColor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM