2011-09-17 52 views
1

我有一个conatiner div,其高度和宽度相对定位。我想在Javascript中计算出它有多少,如果有的话,它的儿童在顶部,右侧,底部和左侧的方向上超出容器div的边缘。任何帮助将非常感激!在Javascript中动态计算溢出量

回答

2

下面的代码为top

var myDivEl = document.getElementById("my-div"); 
var divTop = myDivEl.getBoundingClientRect().top; 

var descendants = myDivEl.getElementsByTagName("*"); 

var tops = []; 
for (var i = 0, descendant; descendant = descendants[i]; ++i) { 
    tops.push(descendant.getBoundingClientRect().top); 
} 

var minTop = Math.min.apply(Math, tops); 

var diff = divTop - minTop; 

更普遍:

function getBoundingClientRectDiff(el, propName, minOrMax) { 
    var propValue = el.getBoundingClientRect()[propName]; 

    var descendants = myDivEl.getElementsByTagName("*"); 

    var descendantPropValues = []; 
    for (var i = 0, descendant; descendant = descendants[i]; ++i) { 
     descendantPropValues.push(descendant.getBoundingClientRect()[propName]); 
    } 

    var extremePropValue = Math[minOrMax].apply(Math, descendantPropValues); 

    return minOrMax === "Max" ? extremePropValue - propValue 
           : propValue - extremePropValue; 
} 

function getBoundingClientRectDiffs(el) { 
    return { 
     top: getBoundingClientRectDiff(el, "top", "Min"), 
     right: getBoundingClientRectDiff(el, "right", "Max"), 
     bottom: getBoundingClientRectDiff(el, "bottom", "Max"), 
     left: getBoundingClientRectDiff(el, "left", "Min") 
    }; 
} 

// use like so: 
var diffs = getBoundingClientRectDiffs(myDivEl); 
console.log(diffs.top, diffs.right, diffs.bottom, diffs.left); 
+0

哇,谢谢你的彻底答复! – VinnyD

+0

Domenic,我怎么能适应这个考虑到子节点的显示属性?基本上,如果一个孩子被设置为显示:无;我想在计算中不包含它或它的任何子节点。 – VinnyD

+0

@VinnyD,你会在'for'循环中添加一个'if(descendant.style.display!==“none”){}',将'descendantPropValues.push(...)'包装起来。 – Domenic

0

你也可以得到一个元素的宽度和scrollWidth或高度和scrollHeight属性的属性之间的区别。