gpt4 book ai didi

javascript - 在 Javascript 中动态计算溢出量

转载 作者:行者123 更新时间:2023-11-30 18:38:51 25 4
gpt4 key购买 nike

我有一个容器 div,其设置的高度和宽度相对定位。我想在 Javascript 中计算出它的子项在顶部、右侧、底部和左侧方向超出容器 div 边缘的程度(如果有的话)。任何帮助将不胜感激!

最佳答案

这是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);

关于javascript - 在 Javascript 中动态计算溢出量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7457781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com