[英]Appending the elements within div using appendchild attribute
I have a div as : 我有一个div:
<div id="div1" width="100px" height="100px">
</div>
Now within this div I want to place 20 elements, but dynamically it can grow upto 50 elements(images) also. 现在在这个div中我想放置20个元素,但动态它也可以增长到50个元素(图像)。
I am using the following code to append these elements in a div, 我使用以下代码将这些元素追加到div中,
var i = document.createElement("img");
var d= document.getElementById("div1");
d.appendchild(i);
Now, the issue is ,as the number of elements increase the elements are going out of div ,and if I use the max-width and max-height on images, the result doesnt change: 现在,问题是,随着元素数量的增加,元素将超出div,如果我在图像上使用max-width和max-height,结果不会改变:
i.setAttribute('max-width', '100%');
i.setAttribute('max-height', '100%');
Is there anything which I am missing? 有什么我想念的吗?
Edit: The images need to shrink as the div size is fixed 编辑:当div大小固定时,图像需要缩小
If the width is fixed and the height is dynamic. 如果宽度是固定的,高度是动态的。 The image will shrink and they will get stacked.
图像会缩小,它们会堆叠起来。 Check my fiddle here
在这里检查我的小提琴
img {
width:100%;
display:inline-block;
}
<div style="width:100px;border: 1px solid black;">
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
</div>
Cant think of a nice way to do it with percentages, 不能想到一个很好的方法来做百分比,
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index= 0,l= count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
its not pretty but should work. 它不漂亮,但应该工作。
i smushed something together from all the answers that fits your needs (if i understand you correctly) 我从所有符合您需求的答案中扼杀了一些东西(如果我理解正确的话)
https://jsfiddle.net/b30d88g6/3/ https://jsfiddle.net/b30d88g6/3/
the div has fixed width/height and the images wont get out of the div div有固定的宽度/高度,图像不会离开div
function add_img() {
var i = document.createElement("img");
i.src= "https://jsfiddle.net/img/logo.png";
var d= document.getElementById("div1");
d.appendChild(i);
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index=0, l=count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.