javascript - 根据其他 child 调整div的宽度?

标签 javascript html css

我真的不知道怎么解释这个,但我会尽力的。

我有一个 div(例如固定为 500px),我希望内容在它们之间平均“分割宽度”。

我该怎么做?

目前,子 div 只占用它们所需的空间,它们不会扩大以填充所有可用宽度的 100%。

最佳答案

你可以这样做:

function getIndividualWidth(elementId,childrenCount){
 var div = document.getElementById(elementId);
 var totalWidth = div.offsetWidth;//500
 //calculating childrenCount would require a function
 //if you were not keeping track of it
 return parseInt(totalWidth / childrenCount);
}

这是计算 div 的子元素的一种方法

function getChildElementCount(element){
 var childCounter = 0;
 var startPoint = element.childNodes;
 for (var child in startPoint) {
  if (startPoint[child].nodeType != 1) continue; //not an element
  childCounter++;
 }
 return childCounter;
}

这会将函数更改为:

function getIndividualWidth(elementId){
 var element = document.getElementById(elementId);
 var totalWidth = element.offsetWidth;//500
 return parseInt(totalWidth / getChildElementCount(element));
}

决定何时使用它取决于您的元素在屏幕上的呈现方式。如果您已经渲染了它们,并且只想从某个父级开始,您可以这样做:

html(跨度是内联元素,因此它们需要 display:inline-block 才能实际反射(reflect)宽度的变化)请在此处查看 jsfiddle:http://jsfiddle.net/uhejM/

<div id="parent" style="width:500px;">
 <span>1</span>
 <span>2</span>
 <span>3</span>
 <span>4</span>
</div>

js

function getIndividualWidth(element){
 return parseInt(element.offsetWidth / getChildElementCount(element));
}

function EqualizeChildWidths(element){
 var width = getIndividualWidth(element);
 var startPoint = element.childNodes;
 for (var child in startPoint) {
  if (startPoint[child].nodeType != 1) continue; //not an element
  startPoint[child].style.width = width + "px";
 }
}    

EqualizeChildWidths(document.getElementById("parent"));

关于javascript - 根据其他 child 调整div的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13964200/

相关文章:

javascript - 使用两个 CSS 文件的深色/浅色模式

javascript - ExtJS - 使用 RegEx 过滤缓冲存储

javascript - 在鼠标悬停时隐藏/显示左侧边栏

javascript - 如何使用 Knockout.js 在鼠标悬停时更改 CSS 类?

javascript - 具有流畅语法和光滑 js 的水平时间线

javascript - 当鼠标在子元素之间移动时,如何不被 mouseover/mouseout 事件垃圾邮件?

javascript - 从包含姓名的字符串中获取姓名缩写和完整姓氏

javascript - CSS 响应式设计 : hiding doesn't make a page from rendering

javascript - 防止CKEditor过滤掉 "tel"协议(protocol)

html - Reset.css 覆盖了 IE7/IE6 中的 colgroup 背景