2011-09-17 71 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屬性的屬性之間的區別。