我有一个conatiner div,其设置高度和宽度相对较低。我想在Javascript中找出多少,如果有的话,它的子项在顶部,右侧,左下方向延伸超出容器div的边缘。任何帮助将不胜感激!
答案 0 :(得分: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);
答案 1 :(得分:0)
您还可以获得元素宽度和scrollWidth或height和scrollHeight属性之间的差异。