javascript - DIV 分成两半并作为子项添加到循环中

标签 javascript jquery html css

我在最近的一次采访中被问到这个问题。

问题陈述 - 给定一个特定宽度和高度的 div,继续向其附加 div,但在附加之前将其大小缩小到一半。直到高度/宽度小于10。附上我的解决方案

let toggle = true;
let border = 0;
container = $('.mainBox');
while (container.height() > 10 || container.width() > 10) {
  if(toggle) {
    container = splitVertically(container); 
    toggle = false;
  } else {
    container = splitHorizontally(container);
    toggle = true;
  }
}     

function splitVertically(container) {
  let $newElem = $('<div>')
    .width(container.width()/2)
    .height(container.height())   
    .css('border-right', 'solid 1px');
  container.append($newElem); 
  return $newElem;
}

function splitHorizontally(container) {
  let $newElem = $('<div>')
    .height(container.height()/2)
    .width(container.width())
    .css('border-bottom', 'solid 1px');
  container.append($newElem);
  return $newElem;
}
  
  
  
.mainBox {
  width: 500px;
  height: 200px;
  /*   background: blue; */
  border: 1px solid;
}

.addBorder {
  border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mainBox"></div>

如果我想将 div 添加到父级的右侧,我该怎么做?

谢谢!

最佳答案

你可以试试把 border-leftfloat:right

let toggle = true;
let border = 0;
container = $('.mainBox');
while (container.height() > 10 || container.width() > 10) {
  if (toggle) {
    container = splitVertically(container);
    toggle = false;
  } else {
    container = splitHorizontally(container);
    toggle = true;
  }
}

function splitVertically(container) {
  let $newElem = $('<div class="pull-right">')
    .width(container.width() / 2)
    .height(container.height())
    .css('border-left', 'solid 1px');
  container.append($newElem);
  return $newElem;
}

function splitHorizontally(container) {
  let $newElem = $('<div class="">')
    .height(container.height() / 2)
    .width(container.width())
    .css('border-bottom', 'solid 1px');
  container.append($newElem);
  return $newElem;
}
.mainBox {
  width: 500px;
  height: 200px;
  /*   background: blue; */
  border: 1px solid;
}

.addBorder {
  border: 1px solid;
}

.pull-right {
  float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mainBox"></div>

关于javascript - DIV 分成两半并作为子项添加到循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49240376/

相关文章:

javascript - Google map 中带有链接的按钮

jQuery .parent() 不起作用

jquery - qtip2 - 单击事件在第一次单击时不起作用

javascript - ckeditor - 将类添加到工具栏按钮的父范围

css - 自定义形状图像容器

javascript - 有什么方法可以返回我的 json 对象

javascript - 当我使用 jQuery 显示/隐藏元素时,如何使用片段来模拟后退按钮

jquery - 标题后的线条和图像,自动计算线条宽度以填充容器

html - 将 SVG 与背景图像对齐

javascript - 是否可以使用php命令更新js文件?