[英]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. 我正在尝试使用myBox类将具有特定高度和宽度以及相同ID的动态fadingIn div动态分配到特定div,并使用
append()
函数append()
它们随机myBox
在myBox
。 However divs are being appended inside and outside myBox
. 但是div附加在
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. 通过查看您的问题,我认为Rory的评论为您提供了答案,但我只是增强了它。 Need to set
overflow: hidden
property of css on main div to stop showing the child objects outside of main div. 需要设置
overflow: hidden
main div上css的overflow: hidden
属性以停止显示main div之外的子对象。
Please review the snippet, or Fiddle here . 请在此处查看代码段或Fiddle 。 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. 追加似乎正确完成,但是我在这里看到的第一个问题是您正在设置顶部和左侧属性,但是未设置position属性。 You should add to your stylesheet something that will specify position attribute for the main container and child divs.
您应该在样式表中添加一些内容,以指定主容器和子div的position属性。 Example:
例:
.myBox {
position: absolute;
}
.myBox div {
position: relative;
}
Also another thing. 也是另一回事。 You specify $newdiv1 as jQuery object:
您将$ newdiv1指定为jQuery对象:
var $newdiv1 = $(...)
And then you again wrap it with $(). 然后再次用$()包装它。 This should be enough:
这应该足够了:
$newdiv1.css({
"top": top,
"left": left
});
$newdiv1.css('background-color', getRandomColor);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.