简体   繁体   English

如何在行内阻止javascript div之间添加换行符?

[英]How can I add a line break between my inline-block javascript divs?

My goal is to display tiles in one large variable grid using html/javascript. 我的目标是使用html / javascript在一个大的可变网格中显示图块。 I've managed to display divs with the inline-block with my code below, but I can't seem to get a line break. 我设法在下面的代码中显示带内嵌块的div,但似乎无法换行。 For example, after each 10 tiles, I would like a new line to start. 例如,每隔10个磁贴,我要换一行。 This would create a 10 by 10 grid. 这将创建一个10 x 10的网格。

function cdiv() {
  var div = document.createElement("div");
  div.style.width = "100px";
  div.style.height = "100px";
  div.style.background = "red";
  div.style.color = "white";
  div.style.display = "inline-block"
  div.innerHTML = 'hello';

  document.body.appendChild(div);
}

for (i = 0; i < 10; i++) {

  for (b = 0; b < 10; b++) { 
    cdiv();
  }
}

I would appreciate a bonus tip in how to give each of these divs a unique ID for further tinkering. 对于如何为这些div中的每个div赋予唯一ID以进行进一步修改,我将不胜感激。

After inner loop , append a break line "br" 内循环后,添加一个换行符“ br”

for (i = 0; i < 10; i++) {
  for (b = 0; b < 10; b++) { 
    cdiv();
  }
  //Append line break here...      
  document.body.appendChild(document.createElement("br")); //Thanks Squint hint as well
}

One approach is to wrap all div in a container which has width 10 times of each div. 一种方法是将所有div包装在一个容器中,该容器的宽度是每个div的10倍。 Please refer to code below and this fiddle. 请参考下面的代码和这个小提琴。 https://jsfiddle.net/5uc2nc3p/2/ https://jsfiddle.net/5uc2nc3p/2/

function cdiv(ele) {
  var div = document.createElement("div");
  div.style.width = "100px";
  div.style.height = "100px";
  div.style.background = "red";
  div.style.color = "white";
  div.style.display = "inline-block"
  div.innerHTML = 'hello';

 ele.appendChild(div);
}

var div = document.createElement("div");
div.style.width = "1000px"; ///10 times of inner divs
div.style["overflow-y"]= "visible"; // to show overflow
document.body.appendChild(div);
for (i = 0; i < 10; i++) {
  for (b = 0; b < 10; b++) { 
    cdiv(div);
  }
}

 <html> <head> <script> function cdiv() { var div = document.createElement("div"); div.style.width = "100px"; div.style.height = "100px"; div.style.background = "red"; div.style.color = "white"; div.style.display = "inline-block" div.innerHTML = 'hello'; document.body.appendChild(div); } </script> </head> <body> <script> for (i = 0; i < 10; i++) { document.body.appendChild(document.createElement("br")); for (b = 0; b < 10; b++) { cdiv(); } } </script> </body> </html> 

document.body.appendChild(document.createElement("br")); use this line to add break in your first loop. 使用此行在您的第一个循环中添加中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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